Flat Preloader Icon

Class Component Vs Functional Component

Feature Class-Based Components Functional Components
State Management State is managed using this.state and this.setState. State is managed using useState hook.
Lifecycle Methods Can use lifecycle methods like componentDidMount, componentDidUpdate, componentWillUnmount, etc. Lifecycle methods are managed using useEffect hook.
' this ' Keyword Requires binding and use of this keyword. No use of 'this' keyword.
Performance Generally has more overhead due to class machinery. Can be more performant due to reduced overhead.
Boilerplate More boilerplate code with constructor and binding. Less boilerplate, cleaner syntax.
Reusability Less straightforward for reusing logic across components. Hooks allow for better reusability of logic (e.g., custom hooks).
Hooks Support Hooks are not used (introduced later, mainly in functional components). Fully supports hooks for state and side effects.
Error Handling Error boundaries can be used to catch errors. Error boundaries are not directly used (can use Error Boundaries at higher levels).

Class-Based Component Example

				
					import React, { Component } from 'react';

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

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

export default Counter;

				
			

Functional Component Example

				
					import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

export default Counter;