Every chapter so far used function components and hooks, which is how new React code is written. Class components still matter for three reasons. Large codebases are full of them. Interviewers still ask you to map lifecycle methods to hooks, because it shows you understand when things run. And one feature still has no hook at all: error boundaries, the subject of the next chapter, can only be written as classes.
This is a reference chapter. It covers enough to read and maintain class code with confidence, maps every lifecycle method to its hook equivalent, and ends with the legacy element APIs (cloneElement, Children, isValidElement) you'll meet in the same codebases. It assumes effects.
The problem: one concern, three methods#
Here's a class component that connects to a chat room. It connects when it mounts and disconnects when it unmounts. Switch rooms and watch the console.
import { Component, useState } from "react";
import { connect, disconnect } from "./chat";
class ChatRoom extends Component<{ roomId: string }> {
componentDidMount() {
connect(this.props.roomId);
}
componentWillUnmount() {
disconnect(this.props.roomId);
}
render() {
return <p>Welcome to #{this.props.roomId}</p>;
}
}
export default function App() {
const [roomId, setRoomId] = useState("general");
return (
<>
<button onClick={() => setRoomId("general")}>general</button>{" "}
<button onClick={() => setRoomId("travel")}>travel</button>
<ChatRoom roomId={roomId} />
</>
);
}The screen says "travel", but the open connection is still general. The class has a mount method and an unmount method, and nothing handles "the prop changed". The fix is a third method, componentDidUpdate, that compares the previous roomId with the current one.
That's the structural weakness of lifecycle methods: they're organized by time (mount, update, unmount), so the code for one concern (being connected to the current room) is split across three places and easy to leave incomplete. An effect organizes by concern instead: one useEffect(() => { connect(roomId); return () => disconnect(roomId); }, [roomId]) covers all three moments, and the dependency array makes "the prop changed" impossible to forget. Keep that contrast in mind; it's the answer to "why did React move to hooks?"
Anatomy of a class component#
A class component extends Component (or PureComponent), reads props from this.props, keeps state in this.state, and returns UI from a render() method. In TypeScript the props and state types are generic parameters.
import { Component } from "react";
type Props = { initialLikes?: number };
type State = { name: string; likes: number };
class Profile extends Component<Props, State> {
// Class field syntax replaces the old constructor(props) { super(props); this.state = ... }
state: State = { name: "Grace", likes: this.props.initialLikes ?? 0 };
// An arrow function field keeps `this` bound when passed as a handler.
like = () => {
this.setState((s) => ({ likes: s.likes + 1 }));
};
render() {
return (
<button onClick={this.like}>
{this.state.name}: {this.state.likes} likes
</button>
);
}
}The this binding is the classic class bug. A regular method passed as onClick={this.like} loses this when React calls it, so this.setState throws. Arrow function fields (or this.like = this.like.bind(this) in the constructor, in older code) fix it.
setState merges, batches, and takes a callback#
this.setState differs from the useState setter in two ways:
- It merges.
this.setState({ likes: 1 })updateslikesand keepsname. The class has one state object and React shallow-merges your partial object into it. AuseStatesetter replaces the value. - It takes an optional callback that runs after the update is committed to the DOM:
this.setState(update, () => ...). Hooks have no direct equivalent; you'd use an effect.
Like the hooks setter, it doesn't change this.state immediately, updates are batched, and the updater form this.setState((state, props) => ...) is the way to build on the previous value.
Click "+2?" once. What do the two console lines say, and what does the button show? Then click "+2 (updater)".
import { Component } from "react";
type State = { name: string; likes: number };
export default class App extends Component<{}, State> {
state: State = { name: "Grace", likes: 0 };
plusTwoWrong = () => {
this.setState({ likes: this.state.likes + 1 });
this.setState({ likes: this.state.likes + 1 }, () => console.log("after commit:", this.state));
console.log("right after setState:", this.state.likes);
};
plusTwoUpdater = () => {
this.setState((s) => ({ likes: s.likes + 1 }));
this.setState((s) => ({ likes: s.likes + 1 }));
};
render() {
return (
<>
<p>
{this.state.name}: {this.state.likes} likes
</p>
<button onClick={this.plusTwoWrong}>+2?</button> <button onClick={this.plusTwoUpdater}>+2 (updater)</button>
</>
);
}
}The lifecycle, mapped to hooks#
Class components expose fixed moments in a component's life as methods. Most map cleanly to hooks; two don't. Step through mount, update and unmount:
Mount. A class runs its constructor, getDerivedStateFromProps and render, React writes the DOM, then componentDidMount runs before paint. A function runs its body; layout effects run before paint and regular effects after.
You can watch the real order with a logger. Every method below prints when React calls it.
import { Component, useState } from "react";
type Props = { count: number };
type State = { doubled: number };
class Logger extends Component<Props, State> {
state: State = { doubled: 0 };
constructor(props: Props) {
super(props);
console.log("constructor");
}
static getDerivedStateFromProps(props: Props, state: State) {
console.log("getDerivedStateFromProps");
return props.count * 2 === state.doubled ? null : { doubled: props.count * 2 };
}
componentDidMount() {
console.log("componentDidMount");
}
shouldComponentUpdate(nextProps: Props) {
console.log("shouldComponentUpdate");
return nextProps.count !== this.props.count; // skip renders that change nothing
}
getSnapshotBeforeUpdate(prevProps: Props) {
console.log("getSnapshotBeforeUpdate");
return `was ${prevProps.count}`;
}
componentDidUpdate(prevProps: Props, prevState: State, snapshot: string) {
console.log("componentDidUpdate, snapshot:", snapshot);
}
componentWillUnmount() {
console.log("componentWillUnmount");
}
render() {
console.log("render");
return <p>count {this.props.count}, doubled {this.state.doubled}</p>;
}
}
export default function App() {
const [count, setCount] = useState(0);
const [, force] = useState(0);
const [shown, setShown] = useState(true);
return (
<>
<button onClick={() => setCount((c) => c + 1)}>count +1</button>{" "}
<button onClick={() => force((n) => n + 1)}>re-render parent only</button>{" "}
<button onClick={() => setShown((s) => !s)}>{shown ? "unmount" : "mount"}</button>
{shown ? <Logger count={count} /> : null}
</>
);
}Click "re-render parent only": getDerivedStateFromProps and shouldComponentUpdate run, the latter returns false, and nothing else does. That's a bail-out.
Here's the full mapping. "Rarely needed" means a pattern the modern docs steer you away from, not one that's gone.
| Class | Hooks equivalent |
|---|---|
constructor, this.state = ... | useState (with a lazy initializer for expensive setup) |
render() | the function body |
componentDidMount | useEffect(fn, []), or useLayoutEffect if you measure DOM before paint |
componentDidUpdate(prevProps) | useEffect(fn, [deps]); the dependency array replaces comparing prevProps by hand |
componentWillUnmount | the cleanup function returned from an effect |
shouldComponentUpdate / PureComponent | memo(Component, areEqual?) |
static getDerivedStateFromProps | rarely needed: compute during render, or reset with a key; at worst, set state during render |
getSnapshotBeforeUpdate | no hook equivalent |
setState(update, callback) | the setter, plus an effect for the "after commit" part |
this.instanceField (non-state values) | useRef |
createRef() | useRef(null) |
static contextType | useContext / use |
getDerivedStateFromError, componentDidCatch | no hook equivalent: error boundaries are classes |
The two methods whose names alone deserve more than a table row:
getDerivedStateFromProps#
A static method (no this) that runs before every render, mount and update, and returns a partial state to merge or null. It exists for the rare case where state must follow a prop: a list that tracks the previous selection and resets it when the items prop changes.
In practice it's mostly misused to copy props into state, which creates two sources of truth (the same bug as copying a controlled prop into state in component patterns). React's own guidance is to reach for alternatives first: compute the value during render, fully control the component from the parent, or reset it with a key.
getSnapshotBeforeUpdate#
Runs after render but right before React applies changes to the DOM, so the DOM still shows the old UI. Whatever it returns is passed as the third argument to componentDidUpdate. The textbook use is preserving scroll position when content is added above what the user is reading:
import { Component, createRef } from "react";
type State = { messages: string[]; older: number };
export default class App extends Component<{}, State> {
state: State = { messages: Array.from({ length: 12 }, (_, i) => `Message ${i + 1}`), older: 0 };
listRef = createRef<HTMLDivElement>();
loadOlder = () =>
this.setState((s) => ({
older: s.older + 5,
messages: [...Array.from({ length: 5 }, (_, i) => `Older ${s.older + 5 - i}`), ...s.messages],
}));
getSnapshotBeforeUpdate(_prevProps: {}, prevState: State) {
const list = this.listRef.current;
if (!list || prevState.messages.length === this.state.messages.length) return null;
return list.scrollHeight - list.scrollTop; // distance from the bottom, measured before the DOM changes
}
componentDidUpdate(_prevProps: {}, _prevState: State, fromBottom: number | null) {
const list = this.listRef.current;
if (list && fromBottom !== null) list.scrollTop = list.scrollHeight - fromBottom;
}
componentDidMount() {
const list = this.listRef.current;
if (list) list.scrollTop = list.scrollHeight; // start at the newest message
}
render() {
return (
<>
<button onClick={this.loadOlder}>Load older</button>
<div ref={this.listRef} style={{ height: 120, overflowY: "auto", overflowAnchor: "none", border: "1px solid #d6d3d1", marginTop: 8 }}>
{this.state.messages.map((m) => (
<div key={m} style={{ padding: "4px 8px" }}>{m}</div>
))}
</div>
</>
);
}
}Scroll to a message, click "Load older", and the message you were reading stays put. Delete the two methods and it jumps. (The list sets overflowAnchor: "none" so you see React's code at work. Modern browsers have CSS scroll anchoring that covers some of these cases on its own, but not all of them, for example when the list is scrolled to the very top.) A function component has no hook for "just before the DOM changes"; the usual workaround is to record the measurement in an event handler before setting state, then restore it in useLayoutEffect.
Fix the chat room from the start of the chapter so that it's always connected to exactly the current room, and nothing when it's closed. Keep it a class component. Press Check.
import { Component, useState } from "react";
import { connect, disconnect } from "./chat";
class ChatRoom extends Component<{ roomId: string }> {
componentDidMount() {
connect(this.props.roomId);
}
componentWillUnmount() {
disconnect(this.props.roomId);
}
render() {
return <p>Welcome to #{this.props.roomId}</p>;
}
}
export default function App() {
const [roomId, setRoomId] = useState("general");
const [open, setOpen] = useState(true);
return (
<>
<button onClick={() => setRoomId("general")}>general</button>{" "}
<button onClick={() => setRoomId("travel")}>travel</button>{" "}
<button onClick={() => setOpen(false)}>Close chat</button>
{open ? <ChatRoom roomId={roomId} /> : null}
</>
);
}Refs in classes#
createRef() creates a { current: null } object once, stored on the instance, and React fills it on mount, just like useRef(null) with a ref attribute. Callback refs (ref={(node) => { this.input = node; }}) work too. Inside a class, "values that persist but don't re-render" are simply instance fields like this.timerId, which is what useRef emulates for functions.
String refs (ref="input" with this.refs.input) were removed in React 19, along with legacy context (contextTypes and getChildContext). If you meet them, the codebase is on React 18 or older.
shouldComponentUpdate and PureComponent#
By default a class component re-renders whenever its parent does. shouldComponentUpdate(nextProps, nextState) lets it say no by returning false. PureComponent is a Component that implements it for you with a shallow comparison of props and state: each key compared with Object.is.
import { Component, PureComponent, useState } from "react";
import { Rendered } from "guide-tools";
type Props = { title: string; tags: string[] };
class PlainRow extends Component<Props> {
render() {
return <Rendered label="Component">{this.props.title}</Rendered>;
}
}
class PureRow extends PureComponent<Props> {
render() {
return <Rendered label="PureComponent">{this.props.title}</Rendered>;
}
}
const tags = ["craft"]; // stable reference
export default function App() {
const [n, setN] = useState(0);
return (
<>
<button onClick={() => setN(n + 1)}>Re-render parent ({n})</button>
<PlainRow title="Refactoring" tags={tags} />
<PureRow title="Refactoring" tags={tags} />
<PureRow title="Refactoring (new array each render)" tags={["craft"]} />
</>
);
}The plain component renders every time. The first PureRow skips, because both props are the same values. The last one re-renders anyway: ["craft"] is a new array on each parent render, so the shallow comparison fails. That's exactly how memo behaves for function components, and the same fixes apply (memoization covers them). Writing shouldComponentUpdate by hand with a deep comparison is a classic way to make things slower, and returning false when something did change leaves stale UI.
Legacy element APIs Legacy#
These live in the react package and still work, but react.dev lists them under "Legacy React APIs" because they make code fragile. You'll see them in class-era component libraries, so you should be able to read them.
Children: helpers for the opaquechildrenprop:Children.map,Children.forEach,Children.count,Children.toArrayandChildren.only. They treatchildrenas a flat list of elements, which is exactly the problem: they can't see components a child renders, only the elements you passed directly.cloneElement(element, props, ...children): returns a copy of an element with props merged in (andkeyandrefpreserved unless overridden). Used to inject props into children.isValidElement(value):trueifvalueis a React element (an object created by JSX orcreateElement), not for strings, numbers or arrays.
Here's the pattern they were used for, and where it breaks:
import { Children, cloneElement, isValidElement, useState, type ReactElement, type ReactNode } from "react";
type OptionProps = { value: string; children: ReactNode; selected?: boolean; onSelect?: (v: string) => void };
function Option({ value, children, selected, onSelect }: OptionProps) {
return (
<button onClick={() => onSelect?.(value)} style={{ fontWeight: selected ? 700 : 400 }}>
{children}
</button>
);
}
function Picker({ children }: { children: ReactNode }) {
const [value, setValue] = useState("craft");
return (
<div>
{Children.map(children, (child) =>
isValidElement(child)
? cloneElement(child as ReactElement<OptionProps>, {
selected: (child as ReactElement<OptionProps>).props.value === value,
onSelect: setValue,
})
: child,
)}
<p>Selected: {value}. Children counted: {Children.count(children)}</p>
</div>
);
}
export default function App() {
return (
<Picker>
<Option value="craft">craft</Option>
<Option value="systems">systems</Option>
{" | "}
<span>
<Option value="teams">teams (wrapped in a span)</Option>
</span>
</Picker>
);
}The first two options work. "teams" never gets selected: cloneElement added the props to the <span>, not to the Option inside it. That's why the compound components chapter uses context instead. The other modern replacements: pass data as props explicitly, accept an array of items with a renderItem function, or let each child read context.
Pitfalls#
Check your understanding#
A class subscribes in componentDidMount, resubscribes in componentDidUpdate when props.userId changes, and unsubscribes in componentWillUnmount. What's the function component version?
An interviewer asks: "How do class lifecycle methods map to hooks, and why did React move away from them?"
Interview angle
Class components keep state in this.state, render from a render() method and update with this.setState, which shallow-merges and batches. Their lifecycle methods are organized by time: mount, update, unmount. Hooks reorganized the same work by concern: one useEffect with a cleanup and a dependency array replaces componentDidMount, componentDidUpdate and componentWillUnmount, and makes the forgotten-update bug much harder. PureComponent maps to memo, createRef to useRef. Two things have no hook: getSnapshotBeforeUpdate and error boundaries, which is why classes still matter.
Map the main class lifecycle methods to hooks.
Is useEffect(fn, []) the same as componentDidMount?
How does this.setState differ from a useState setter?
Why did React move from classes to hooks?
What is getDerivedStateFromProps for, and why is it usually the wrong tool?
What does getSnapshotBeforeUpdate do, and how would you get the same result with hooks?
Recap#
- Class components keep state in
this.state, render fromrender(), and update withthis.setState, which shallow-merges, batches, and accepts an after-commit callback. - Lifecycle methods are organized by time; effects are organized by concern. Mount, update and unmount methods together map to one
useEffectwith a cleanup and dependencies. componentDidMountandcomponentDidUpdaterun before paint, likeuseLayoutEffect.getSnapshotBeforeUpdateand the error boundary methods have no hook equivalent.PureComponentandshouldComponentUpdateskip renders, likememo, with the same shallow-comparison traps.getDerivedStateFromPropsis rarely the right tool.Children,cloneElementandisValidElementare legacy: they only see direct children. Prefer context, explicit props or render functions.
Sources#
- react.dev: Component, including every lifecycle method and migration examples
- react.dev: PureComponent and createRef
- react.dev: Legacy React APIs:
Children,cloneElement,isValidElement - react.dev: React 19 upgrade guide (removed string refs and legacy context)
- Facts checked November 24, 2026.