React Class Components

  • A React class component is a JavaScript class that extends React.Component.
  • It was the primary way to create components before the introduction of Hooks.

Creating a Simple Class Component

Class components have a render method where the UI structure is defined. Example:

import React, { Component } from 'react';

class Greeting extends Component {
  render() {
    return <h1>Hello, Coder!</h1>;
  }
}

State in Class Components

Class components can have a state, which is an object that stores dynamic data.

import React, { Component } from 'react';

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

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

Lifecycle Methods in Class Components

Class components have lifecycle methods that provide hooks into different stages of a component's life.

import React, { Component } from 'react';

class LifecycleDemo extends Component {
  componentDidMount() {
    console.log('Component did mount!');
  }

  componentWillUnmount() {
    console.log('Component will unmount!');
  }

  render() {
    return <p>Component with lifecycle methods.</p>;
  }
}

Class Components vs Functional Components

With the introduction of Hooks, functional components can now manage state and have lifecycle behaviors, reducing the necessity of class components.

When to Use Class Components

Class components are still relevant, especially for codebases that haven't fully adopted Hooks.

 

Summary

Understanding class components is valuable for working with older codebases and transitioning to modern React development practices. As the React ecosystem evolves, functional components with Hooks have become the standard for building components.