How to Implement Class Components in React

This article provides a straightforward, step-by-step guide on how to implement class components in React. You will learn the fundamental syntax required to create a class component, how to initialize and manage local state, how to pass and access props, and how to utilize key lifecycle methods.

Creating a Basic Class Component

To define a class component in React, you must create an ES6 class that extends React.Component. The class must contain a render() method, which returns the JSX that defines the UI of the component.

import React from 'react';

class Welcome extends React.Component {
  render() {
    return <h1>Hello, World!</h1>;
  }
}

export default Welcome;

Managing State in Class Components

Unlike functional components that use the useState hook, class components manage state using a local state object initialized inside the class constructor. You must call super(props) inside the constructor before any other statement to ensure this.props is defined.

To update the state, you must use the this.setState() method, which schedules an update to the component’s state object and triggers a re-render.

import React from 'react';

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

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }

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

export default Counter;

Using Props in Class Components

Props are passed to class components just like they are to functional components. To access props inside a class component, you use the this.props object.

import React from 'react';

class UserProfile extends React.Component {
  render() {
    return (
      <div>
        <h2>User: {this.props.username}</h2>
        <p>Status: {this.props.status}</p>
      </div>
    );
  }
}

// Usage: <UserProfile username="Alex" status="Active" />
export default UserProfile;

Implementing Lifecycle Methods

Class components have built-in lifecycle methods that allow you to run code at specific points in a component’s life. The three most commonly used lifecycle methods are:

import React from 'react';

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

  componentDidMount() {
    this.interval = setInterval(() => {
      this.setState(prevState => ({ seconds: prevState.seconds + 1 }));
    }, 1000);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.seconds !== this.state.seconds) {
      console.log(`Timer updated to: ${this.state.seconds}`);
    }
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    return <h1>Seconds Passed: {this.state.seconds}</h1>;
  }
}

export default Timer;