12. Class Components

Class Components in React

Overview

In React, components are the building blocks of your application. They can be created using two primary syntaxes: Class Components and Functional Components. Both types of components serve the same fundamental purpose, which is to define reusable UI elements. However, they have some differences and similarities:

Differences:

Syntax

State

Lifecycle Methods

Similarities:

Considerations:

Since the introduction of hooks, functional components have become the preferred way to write components in React due to their simplicity and the ability to use state and lifecycle features. However, class components are still widely used in existing codebases and can be useful in certain situations, especially when dealing with legacy code.

If you are starting a new React project or working on a codebase using React 16.8 or later, it's recommended to use functional components with hooks for their simplicity and the direction in which React development is heading.

Class Component Constructor

The constructor in a class component has two main purposes:

  1. To initialize state.
  1. To bind functions to the class component.

Example:

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

    // Bind function to class component
    this.handleIncreaseCounterClick = this.handleIncreaseCounterClick.bind(this);
  }

  handleIncreaseCounterClick() {
    this.setState({ count: this.state.count + 1 });
  }

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

Class Component Lifecycle Methods

Example:

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

    // Bind function to class component
    this.handleIncreaseCounterClick = this.handleIncreaseCounterClick.bind(this);
  }

  componentDidMount() {
    console.log('Component has been mounted to the DOM');
  }

  componentDidUpdate() {
    console.log('Component has been updated');
  }

  componentWillUnmount() {
    console.log('Component will be unmounted from the DOM');
  }

  handleIncreaseCounterClick() {
    this.setState({ count: this.state.count + 1 });
  }

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

For more examples and a practical application of Class Components in React, you can refer to this example on CodeSandbox: codesandbox.io/s/tmtv63?file=/App.js&utm_medium=sandpack.

Reference

The content in this document is based on the original notes provided in Azerbaijani. For further details, you can refer to the original document using the following link:

Original Note - Azerbaijani Version