What Are Class Components?

Class Components are one of the two types of components in React. They were the main way to create components before Functional Components became popular with the introduction of React Hooks. Class Components are based on ES6 classes and are more complex compared to Functional Components.

You should know about Class Components because:

  • Legacy Code: You might come across them in older React codebases.
  • Understanding React History: It helps to know how React components have evolved.

Creating a Class Component

Here’s how you create a basic Class Component:


import React, { Component } from 'react';

class Welcome extends Component {
  render() {
    return (
      <div>
        <h1>Welcome to My React App</h1>
      </div>
    );
  }
}

export default Welcome;
      

Explanation:

  • Importing React and Component: We start by importing React and Component from the 'react' library. Component is a class provided by React that we extend to create our own component.
  • Creating a Class Component: We define a new class called Welcome that extends Component. This means our Welcome class inherits properties and methods from React's Component.
  • The render Method: Every Class Component must have a render method. This method returns the JSX that defines what the component will display. In this example, it simply returns a <div> with a heading.
  • Exporting the Component: We use export default to make our component available for use in other parts of the application.

State in Class Components

One of the main features of Class Components is state. State is used to store information that can change over time and affect how the component behaves or looks.

Here’s an example of a Class Component with state:


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>
        <h1>Count: {this.state.count}</h1>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

export default Counter;
      

Explanation:

  • Constructor Method: The constructor method is used to initialize the component's state. We callsuper(props) to ensure the parent Component class is properly initialized. this.state is used to set the initial state.
  • State Object: this.state is an object where we store the component's data. In this case, we start with count set to 0.
  • Updating State: We use this.setState to update the state. When this.setStateis called, React re-renders the component with the new state. Here, the increment method increases the count by 1.
  • Rendering State: Inside the render method, we access the state using this.state.countand display it in the <h1> tag. The button uses an onClick event to call the increment method when clicked.

Lifecycle Methods

Class Components have special methods called lifecycle methods that you can use to run code at specific points in a component's life. These methods allow you to handle things like data fetching, manual DOM manipulation, and cleanup.

Here’s an example of a Class Component using a lifecycle method:


import React, { Component } from 'react';

class LifecycleExample extends Component {
  componentDidMount() {
    console.log('Component has been rendered to the DOM');
  }

  render() {
    return (
      <div>
        <h1>Lifecycle Example</h1>
      </div>
    );
  }
}

export default LifecycleExample;
      

Explanation:

  • Lifecycle Method: componentDidMount is a lifecycle method that runs after the component has been rendered to the DOM. It’s often used to fetch data or perform setup tasks.

Why Use Functional Components Instead?

Functional Components have become the preferred way to create components in React, thanks to their simplicity and the introduction of React Hooks. Hooks allow you to use state and other features without writing a class.

  • Simplicity: They are easier to read and write.
  • Hooks: Allow you to use state and other features without classes.
  • Less Boilerplate: No need for constructor or this.

Summary

Class Components were the primary way to create components in React before Functional Components and Hooks were introduced. They use classes and have features like state and lifecycle methods. Although you will mainly work with Functional Components in modern React development, understanding Class Components is useful for reading and maintaining older code.