Sub topic 15
Class components and why you may still see them
This chapter assumes you can write function components, pass props, and use useState. It also assumes you know the basics of JavaScript classes (extends, methods, this). You will not write new class components in modern React, but you will read them in older codebases and in one case still need one.
What a class component looks like
A class component is a JavaScript class that extends Component and defines a render method. render returns the same JSX a function component would return. Props arrive as this.props, and local state lives in this.state.
import { Component } from 'react';
class Counter extends Component {
state = { count: 0 };
handleClick = () => {
this.setState((prev) => ({ count: prev.count + 1 }));
};
render() {
return (
<button onClick={this.handleClick}>
{this.props.label} {this.state.count} times
</button>
);
}
}
export default function App() {
return <Counter label="Clicked" />;
}The function version of this component is the Counter from the state chapter. Compare the two.
| Idea | Function component | Class component |
|---|---|---|
| Read props | `function Card({ title })` | `this.props.title` |
| Declare state | `useState(0)` | `state = { count: 0 }` |
| Update state | `setCount(count + 1)` | `this.setState({ count: ... })` |
| Output UI | `return <div />` | `render() { return <div /> }` |
Common errors with `this`
Inside a class, this depends on how a method is called. If you pass a normal method as an event handler, React calls it without the instance, and this is undefined. This causes the classic error "Cannot read properties of undefined (reading 'setState')".
There are two fixes. The first is an arrow-function class field, as handleClick is above. The second is binding in the constructor with this.handleClick = this.handleClick.bind(this).
Do not assign to this.state after the first render. this.state.count = 5 changes the value but does not trigger a re-render. Always call setState.
setState also merges the object you pass into the existing state. A useState setter replaces the whole value instead. This difference trips people moving between the two styles.
Lifecycle methods
Class components run code at fixed points in a component's life through lifecycle methods. Function components do this with useEffect.
componentDidMountruns once after the first render. Code that fetches data or starts a timer usually goes here.componentDidUpdateruns after each later render.componentWillUnmountruns before removal. Use it to clean up timers and subscriptions.
The one case that still needs a class
React has no function-component equivalent of componentDidCatch and getDerivedStateFromError. An error boundary catches errors thrown while rendering its children and shows a fallback. It must be a class.
import { Component } from 'react';
export class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info.componentStack);
}
render() {
if (this.state.hasError) {
return <p>Something went wrong.</p>;
}
return this.props.children;
}
}Wrap part of your app in <ErrorBoundary> and write everything else as function components. Many projects use a library such as react-error-boundary so they never write this class themselves.
Reading legacy code
When you meet a class component, translate it in your head. Treat this.props as props and this.state as state. Treat setState as a state setter, and the lifecycle methods as effects. Everything else, including JSX, keys, children, and composition, works the same way.
Exercise
A class component passes this.handleSave to onClick, and clicking throws "Cannot read properties of undefined (reading 'setState')". Why does this happen, and how do you fix it?
Show answer
A normal class method loses its this binding when React calls it as an event handler, so this is undefined. Fix it by defining the handler as an arrow-function class field (handleSave = () => { ... }) or by binding it in the constructor with this.handleSave = this.handleSave.bind(this).
Exercise
Which feature can you currently build only with a class component, and what does it do?
Show answer
An error boundary. It uses static getDerivedStateFromError and componentDidCatch to catch errors thrown while rendering its children and show a fallback UI.