Sub topic 15
Class components and why you may still see them
This chapter assumes you can read function components, JSX, props, and useState, and that you know JavaScript classes (class, extends, this, constructor). The goal is to read class components in existing code, translate them to function components, and recognize the one job that still needs a class.
Where class components fit
Before React 16.8 (2019), a component needed a class to hold state or run code at specific moments in its life. Hooks such as useState and useEffect moved those abilities into function components. React's documentation now recommends function components for new code, and class components remain supported. You will meet them in three places:
- Older codebases written before hooks.
- Tutorials, Stack Overflow answers, and library source that predate hooks.
- Error boundaries, which still require a class.
Rewriting working class components is optional. Read them fluently, and write new components as functions.
Anatomy of a class component
A class component extends React.Component and defines a render method that returns JSX. Props arrive on this.props, and state lives on this.state.
import { Component } from 'react';
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count: props.initial ?? 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState((prev) => ({ count: prev.count + 1 }));
}
render() {
return (
<button onClick={this.handleClick}>
{this.props.label}: {this.state.count}
</button>
);
}
}
export default function App() {
return <Counter label="Clicks" initial={5} />;
}Several details differ from function components:
super(props)must be the first statement in the constructor. Without it,this.propsis undefined inside the constructor.- State is always one object. You read it as
this.state.count, not as a separate variable. - You change state only through
this.setState. Assigningthis.state.count = 1outside the constructor does nothing visible, because React is never told to re-render. setStatemerges the object you pass into the existing state. TheuseStatesetter replaces the value instead.- When the new state depends on the old state, pass a function, as the example does. State updates are batched, so reading
this.stateright after callingsetStatecan return the old value.
The `this` problem
JavaScript decides what this means when a method is called, not when it is defined. React calls your event handler later as a plain function, so this inside it is undefined. Writing onClick={this.handleClick} without extra work makes this.setState throw a TypeError.
There are two common fixes. The first is the bind call in the constructor, shown above. The second is a class field holding an arrow function, which captures this from the instance:
import { Component } from 'react';
class Toggle extends Component {
state = { on: false };
handleClick = () => {
this.setState((prev) => ({ on: !prev.on }));
};
render() {
return (
<button onClick={this.handleClick}>
{this.state.on ? 'On' : 'Off'}
</button>
);
}
}
export default Toggle;Here state = {...} replaces the constructor, and handleClick = () => {...} needs no binding. Both forms are common in older code. Function components avoid this whole category of bug because they have no this.
Lifecycle methods
A class component can run code at set moments by defining specific methods. These are the ones you will see most often.
| Method | When React calls it | Typical use |
|---|---|---|
| `constructor` | Once, before the first render | Set initial state, bind methods |
| `render` | On every mount and update | Return JSX. Must be pure |
| `componentDidMount` | After the first render is in the DOM | Fetch data, start timers, subscribe |
| `componentDidUpdate(prevProps, prevState)` | After each update, not the first render | React to changed props or state |
| `componentWillUnmount` | Just before removal from the DOM | Clear timers, unsubscribe |
Here is a clock that uses the mount and unmount methods to start and stop a timer:
import { Component } from 'react';
class Clock extends Component {
state = { now: new Date() };
componentDidMount() {
this.timerId = setInterval(() => {
this.setState({ now: new Date() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.timerId);
}
render() {
return <p>{this.state.now.toLocaleTimeString()}</p>;
}
}
export default Clock;Forgetting componentWillUnmount leaves the interval running after the component is gone. It keeps calling setState on a component that no longer exists and leaks memory.
The same component as a function
The clock translates to a function component with useState and useEffect:
import { useState, useEffect } from 'react';
export default function Clock() {
const [now, setNow] = useState(new Date());
useEffect(() => {
const timerId = setInterval(() => setNow(new Date()), 1000);
return () => clearInterval(timerId);
}, []);
return <p>{now.toLocaleTimeString()}</p>;
}Setup and cleanup now sit together in one effect. In the class version, the timer is started in one method and stopped in another, with this.timerId carrying it between them. The empty dependency array [] makes the effect run once after mount, and the returned function runs on unmount.
The mapping is not one to one, so do not translate method by method:
| Class component | Function component |
|---|---|
| `this.props.name` | `name` from the parameter list |
| `this.state` and `this.setState` | One `useState` call per independent value |
| `componentDidMount` | `useEffect` with `[]` |
| `componentWillUnmount` | Cleanup function returned from `useEffect` |
| `componentDidUpdate` | `useEffect` with a dependency list |
| Instance fields such as `this.timerId` | `useRef`, or a variable inside the effect |
An effect is organized around what it synchronizes with, not around when it runs. Splitting one class's componentDidMount, componentDidUpdate, and componentWillUnmount into several focused effects is usually the right result.
Error boundaries: the remaining use for classes
If a component throws while rendering, React removes the whole tree by default and leaves a blank page. An error boundary is a component that catches such errors in its children and shows a fallback. React has no hook for this, so an error boundary must be a class that defines static getDerivedStateFromError, componentDidCatch, or both.
import { Component } from 'react';
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error('Caught by boundary:', error, info.componentStack);
}
render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
function Broken() {
throw new Error('Something failed while rendering');
}
export default function App() {
return (
<ErrorBoundary fallback={<p>Something went wrong.</p>}>
<Broken />
</ErrorBoundary>
);
}getDerivedStateFromError runs during rendering and returns the state that switches the boundary to its fallback. componentDidCatch runs afterward and is the place for side effects such as logging. Most projects write this class once, or use a library that provides one, and keep every other component as a function.
Common mistakes when working with classes
- Passing
this.handleClickwith no binding and no arrow function. The result isthisbeingundefinedwhen the handler runs. - Calling
this.setStateinsiderender. This triggers another render and causes an infinite loop.rendermust stay pure. - Mutating state directly, such as
this.state.items.push(x). Create a new array and pass it tosetState. - Calling
setStateincomponentDidUpdatewithout a condition that compares toprevPropsorprevState. This also loops forever. - Mixing styles. A class component cannot use hooks, and calling
useStateinside one throws an error. To share logic between a class and a function, move it into a plain function or a custom hook and convert the class.
Exercises
Exercise
A class component passes onClick={this.save} to a button, and clicking it throws "Cannot read properties of undefined (reading 'setState')". Name the cause and give two ways to fix it.
Show answer
The method is called without its instance, so this is undefined inside save. Fix it by binding in the constructor (this.save = this.save.bind(this)), or by defining the method as a class field arrow function (save = () => {...}). Wrapping the call as onClick={() => this.save()} also works.
Exercise
Rewrite this class as a function component. Keep the same behavior, including cleanup. class Title extends Component { componentDidMount() { document.title = this.props.text; } componentDidUpdate(prev) { if (prev.text !== this.props.text) document.title = this.props.text; } render() { return <h1>{this.props.text}</h1>; } }
Show answer
function Title({ text }) {
useEffect(() => {
document.title = text;
}, [text]);
return <h1>{text}</h1>;
}
The single effect with the dependency [text] replaces both lifecycle methods. It runs after the first render and after every change to text. No cleanup is needed because setting a title does not create anything that must be released.
Exercise
Why can't you convert an error boundary to a function component?
Show answer
React provides no hook equivalent to getDerivedStateFromError and componentDidCatch. Only a class component can define them, so error boundaries are still written as classes, even in projects where every other component is a function.