Flat Preloader Icon

Class Components

Class components in React are the older way of writing components that can have their own state and lifecycle methods. Before the introduction of hooks in functional components, class components were the primary way to handle state and side effects.

Basic Class Component

				
					import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

export default Greeting;

				
			

State in Class Components

Class components can have their own state, which is managed using the this.state property and updated using the this.setState method.
				
					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>You clicked {this.state.count} times</p>
        <button onClick={this.increment}>
          Click me
        </button>
      </div>
    );
  }
}

export default Counter;

				
			

Lifecycle Methods

Class components have several lifecycle methods that can be overridden to run code at specific points in the component’s lifecycle.
  • componentDidMount: Called once, immediately after the component is mounted.
  • componentDidUpdate: Called immediately after updating occurs.
  • componentWillUnmount: Called just before the component is unmounted and destroyed.

Advantages and Disadvantages of Class Components

Advantages :

  1. State and Lifecycle Methods: Class components can manage state and have lifecycle methods.
  2. Inheritance: They provide a more traditional OOP approach, which might be familiar to developers coming from other OOP languages.

Disadvantages :

  1. Boilerplate: They tend to have more boilerplate code compared to functional components.
  2. Complexity: Managing this keyword can sometimes lead to bugs and confusion.
  3. Performance: They may have a slight performance overhead compared to functional components with hooks.