TExcelTAD
Home › React › React Class Components

React Class Components

Before hooks arrived in React 16.8 (2019), components that needed state or lifecycle logic had to be written as classes. New code uses function components, but you will still meet classes in older codebases, tutorials and libraries — and error boundaries can still only be written as classes. This lesson teaches you to read them.

Note: Class components are a legacy API. They still work in React 19, but the React team recommends function components for all new code.

Anatomy of a class component

jsx · try it yourself
import { Component } from 'react';

class Welcome extends Component {
  render() {
    return <h2>Hello, {this.props.name}!</h2>;
  }
}

export default function App() {
  return (
    <div>
      <Welcome name="Quang" />
      <Welcome name="Thao" />
    </div>
  );
}
  • The class extends Component (or React.Component).
  • It must have a render() method that returns JSX.
  • Props are available as this.props.

State and setState

Class state is a single object stored in this.state. You change it with this.setState(), which merges the object you pass into the existing state:

jsx · try it yourself
import { Component } from 'react';

class Counter extends Component {
  state = { count: 0, step: 1 };

  increment = () => {
    this.setState((prev) => ({ count: prev.count + prev.step }));
  };

  render() {
    const { count, step } = this.state;
    return (
      <div>
        <p style={{ fontSize: 24 }}>Count: {count}</p>
        <button onClick={this.increment}>+{step}</button>{' '}
        <button onClick={() => this.setState({ step: step === 1 ? 10 : 1 })}>
          Switch step to {step === 1 ? 10 : 1}
        </button>
      </div>
    );
  }
}

export default function App() {
  return <Counter />;
}

Note that increment is written as an arrow function class field. A normal method would lose its this when passed as onClick={this.increment}. Older code fixes this with this.increment = this.increment.bind(this) inside a constructor.

Lifecycle methods

Classes react to the component's life through special methods:

Method When it runs Hook equivalent
constructor(props) before the first render useState initializer
render() every render the function body
componentDidMount() after the first render is on screen useEffect(fn, [])
componentDidUpdate(prevProps, prevState) after every re-render useEffect(fn, [deps])
componentWillUnmount() just before removal the effect's cleanup function
shouldComponentUpdate() before a re-render, can skip it memo
static getDerivedStateFromError() / componentDidCatch() a child threw while rendering none — classes only

Here is a timer that starts on mount and is cleaned up on unmount:

jsx · try it yourself
import { Component, useState } from 'react';

class Stopwatch extends Component {
  state = { seconds: 0 };

  componentDidMount() {
    console.log('mounted: starting timer');
    this.timer = setInterval(() => {
      this.setState((s) => ({ seconds: s.seconds + 1 }));
    }, 1000);
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.seconds !== this.state.seconds && this.state.seconds % 5 === 0) {
      console.log(`updated: ${this.state.seconds} seconds`);
    }
  }

  componentWillUnmount() {
    console.log('unmounting: clearing timer');
    clearInterval(this.timer);
  }

  render() {
    return <p style={{ fontSize: 28, fontFamily: 'monospace' }}>⏱ {this.state.seconds}s</p>;
  }
}

export default function App() {
  const [visible, setVisible] = useState(true);
  return (
    <div>
      <button onClick={() => setVisible(!visible)}>{visible ? 'Remove' : 'Show'} stopwatch</button>
      {visible && <Stopwatch />}
    </div>
  );
}

The same component, two ways

Comparing side by side makes it easy to translate old code:

jsx
// Class
class Toggle extends Component {
  state = { on: false };
  componentDidUpdate() {
    document.title = this.state.on ? 'ON' : 'OFF';
  }
  render() {
    return (
      <button onClick={() => this.setState({ on: !this.state.on })}>
        {this.state.on ? 'ON' : 'OFF'}
      </button>
    );
  }
}

// Function + hooks
function Toggle() {
  const [on, setOn] = useState(false);
  useEffect(() => {
    document.title = on ? 'ON' : 'OFF';
  }, [on]);
  return <button onClick={() => setOn(!on)}>{on ? 'ON' : 'OFF'}</button>;
}

The function version is shorter, has no this, and keeps related logic together instead of spreading it across lifecycle methods.

Why hooks replaced classes

  • No this confusion — no binding, no forgotten this.
  • Reusable logic — custom hooks share stateful logic; classes needed awkward patterns like higher-order components
  • Grouped by concern — one effect holds both setup and cleanup instead of splitting it across componentDidMount and componentWillUnmount
  • Less code to write and read

Tip: You don't need to rewrite working class components. Just write new components as functions — both kinds can be mixed freely in one app.

Test yourself

Which method must every class component define?

  1. constructor
  2. componentDidMount
  3. render
  4. setState

What does this.setState({ step: 10 }) do to other keys in the state object?

  1. Deletes them
  2. Keeps them — the object is merged
  3. Resets them to their initial values
  4. Throws an error

Which hook pattern corresponds to componentWillUnmount?

  1. useState initializer
  2. The cleanup function returned from useEffect
  3. useMemo
  4. useRef