Projects

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:

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:

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:

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:

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.

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.