Hack Frontend Community

Difference Between Functional and Class Components in React

What Are Components in React?

Components are building blocks of React application. They can be:

  • Functional — regular JavaScript functions
  • Class-based — classes inheriting React.Component

Main Differences

Functional componentsClass components
Syntaxfunction MyComponent() class MyComponent extends React.Component
State supportYes (via useState, useReducer)Yes (via this.state)
LifecycleThrough hooks (useEffect)Methods (componentDidMount, etc.)
ContextuseContext()this.context
thisNo thisUses this
Code brevityshorter and simplermore verbose
Hooks supportYesNo
Performance (theoretically)Slightly higherSlightly lower

Functional Component Example

import { useState, useEffect } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component rendered");

    return () => {
      console.log("Component unmounted");
    };
  }, []);

  return (
    <div>
      <p>Counter: {count}</p>
      <button onClick={() => setCount(count + 1)}>+</button>
    </div>
  );
}

Class Component Example

import React from "react";

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidMount() {
    console.log("Component rendered");
  }

  componentWillUnmount() {
    console.log("Component unmounted");
  }

  render() {
    return (
      <div>
        <p>Counter: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          +
        </button>
      </div>
    );
  }
}

When to Use

  • Functional components — modern standard. Used in 99% of cases, especially with hooks.
  • Class components — in legacy projects or when working with legacy code.

Conclusion

  • Functional components are simpler and more convenient, especially with hooks appearance.
  • Class components are considered outdated and used only for backward compatibility.
  • All new projects are recommended to be written only using functional components.