Lesson

React Class Components

10 min reading
Free Course

React Class Components: Understanding Legacy Classes and Lifecycle Methods

React class components were the only way to hold local state and run lifecycle code until React 16.8 introduced Hooks. A class component extendsReact. Component, defines a render() method that returns JSX, and manages its data through this. state and this.setState(). Most new code is written with function components, but you will still meet classes in older projects, so this lesson shows how they work and how they map to Hooks.

Why Learn React Class Components Today?

There are two practical reasons. The first is maintenance: many production apps were built before 2019 and still contain class-based screens. Reading them confidently and migrating them safely is a common job. The second is Error Boundaries. React still requires class syntax for components that catch rendering errors in their children, so you can't avoid classes completely even in a modern codebase.

Anatomy of a React Class Component

The example below is a small timer. It shows the four things most class components do: initialize state, start work after mounting, clean up before unmounting, and render JSX.

import { Component } from 'react';

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

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

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

  render() {
    return (
      <section>
        <h2>Elapsed Time: {this.state.seconds}s</h2>
      </section>
    );
  }
}

Here is what each part does:

  • constructor(props) must call super(props) first. Without it, this. props is not set up properly inside the constructor. Initial state is assigned here with a plain object.

  • componentDidMount() runs once after the component first appears on screen. It is the right place to start timers, open subscriptions, or fetch data.

  • this.setState(...)is used with a function here because the new value depends on the previous one. React may batch state updates, so reading this. state right after calling setState can give you a stale value. The updater form always receives the latest state.

  • componentWillUnmount() runs just before the component is removed. Clearing the interval prevents the timer from running after the component is gone.

  • render() Describes the UI. It should only calculate and return JSX, with no side effects.

How to Check It Works

Add console.log('timer started') in componentDidMount and console.log('timer cleared') in componentWillUnmount , then render and remove the component. You should see each message once per mount and unmount. In development, <StrictMode> intentionally mounts, unmounts, and remounts components to expose missing cleanup so that you may see the pair twice. If cleanup is correct, that is harmless.

Lifecycle Methods Mapped to Hooks

Class components expose explicit lifecycle hooks such as componentDidMount for fetching data or starting timers, componentDidUpdate for reacting to prop changes, and componentWillUnmount for cleaning up subscriptions before removal. Understanding this mapping makes migrating older screens to function components straightforward.

Class Lifecycle

Modern Hook Equivalent

Purpose

constructor / this.state

useState

Initialize local state

componentDidMount

useEffect(..., [])

Run code after mount

componentDidUpdate

useEffect(..., [deps])

React to prop/state changes

componentWillUnmount

Cleanup inside useEffect

Clear timers and listeners

Common Class Component Mistakes

  • Mutating this.state Directly: Writing this.state.seconds = 5 never triggers a re-render. Always call this.setState(...).

  • Forgetting this Binding on Methods: Passing onClick={this.handleClick} on a regular class method loses this context unless you bind it in the constructor or use an arrow class field.

  • Using Deprecated Lifecycles: Methods like componentWillMount and componentWillReceiveProps cause race conditions in concurrent rendering and should be replaced.

Frequently Asked Questions

Should I write new features using class components?

No. React recommends function components with Hooks for all new components because hooks avoid this binding bugs and simplify logic reuse.

Are class components completely removed in React 19?

No. Class components still work in React 19, and Error Boundaries (componentDidCatch and getDerivedStateFromError) still require class syntax.

Does this.setState overwrite all state properties?

No. Unlike the useState setter, this.setState performs a shallow merge with existing this.state properties.

Save Your Progress

Unlock Your
Full Potential.

Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.

Quick Access With

Enterprise-Grade Security Protocol
Lesson Recap Quiz Available

Test Your Knowledge

You've completed this section! Take a quick 5-question quiz to check your understanding.

React Topic Hub

Stuck on this lesson?

Join our community of senior developers.

Ask in Forum