Class components

Lifecycles, mapped to hooks. Still asked, still needed.

Builds on Effects.

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.

A class component that forgot about updates
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} />
    </>
  );
}
Nothing logged yet.

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 }) updates likes and keeps name. The class has one state object and React shallow-merges your partial object into it. A useState setter 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.

PredictTwo setStates and a log

Click "+2?" once. What do the two console lines say, and what does the button show? Then click "+2 (updater)".

setState batching and merging
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>
      </>
    );
  }
}
Nothing logged yet.

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:

Class lifecycle next to the hooks timeline
Class componentFunction with hooksrenderconstructoruseState initializersstatic getDerivedStateFromPropsshouldComponentUpdatememo comparisonrender()the function bodypre-commitgetSnapshotBeforeUpdate(no hook equivalent)commitReact writes the changes to the DOMlayoutcomponentDidMount / DidUpdateuseLayoutEffectpaintThe browser paintsafter paint(nothing)useEffectunmountcomponentWillUnmounteffect cleanups
Step 1 of 4

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.

Every lifecycle method, logged
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}
    </>
  );
}
Nothing logged yet.

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.

ClassHooks equivalent
constructor, this.state = ...useState (with a lazy initializer for expensive setup)
render()the function body
componentDidMountuseEffect(fn, []), or useLayoutEffect if you measure DOM before paint
componentDidUpdate(prevProps)useEffect(fn, [deps]); the dependency array replaces comparing prevProps by hand
componentWillUnmountthe cleanup function returned from an effect
shouldComponentUpdate / PureComponentmemo(Component, areEqual?)
static getDerivedStateFromPropsrarely needed: compute during render, or reset with a key; at worst, set state during render
getSnapshotBeforeUpdateno 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 contextTypeuseContext / use
getDerivedStateFromError, componentDidCatchno 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:

Keeping the scroll position when older messages load
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 itFollow the room

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.

ChatRoom as a class
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.

PureComponent skips renders when props are shallowly equal
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 opaque children prop: Children.map, Children.forEach, Children.count, Children.toArray and Children.only. They treat children as 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 (and key and ref preserved unless overridden). Used to inject props into children.
  • isValidElement(value): true if value is a React element (an object created by JSX or createElement), not for strings, numbers or arrays.

Here's the pattern they were used for, and where it breaks:

cloneElement injecting props, and the wrapper that breaks it
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#

Quick checkLifecycle to hook

A class subscribes in componentDidMount, resubscribes in componentDidUpdate when props.userId changes, and unsubscribes in componentWillUnmount. What's the function component version?

Explain it out loudLifecycles versus hooks

An interviewer asks: "How do class lifecycle methods map to hooks, and why did React move away from them?"

Interview angle

Say it in 30 seconds

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.

basic

Is useEffect(fn, []) the same as componentDidMount?

intermediate

How does this.setState differ from a useState setter?

basic

Why did React move from classes to hooks?

intermediate

What is getDerivedStateFromProps for, and why is it usually the wrong tool?

senior

What does getSnapshotBeforeUpdate do, and how would you get the same result with hooks?

senior

Recap#

  • Class components keep state in this.state, render from render(), and update with this.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 useEffect with a cleanup and dependencies.
  • componentDidMount and componentDidUpdate run before paint, like useLayoutEffect. getSnapshotBeforeUpdate and the error boundary methods have no hook equivalent.
  • PureComponent and shouldComponentUpdate skip renders, like memo, with the same shallow-comparison traps. getDerivedStateFromProps is rarely the right tool.
  • Children, cloneElement and isValidElement are legacy: they only see direct children. Prefer context, explicit props or render functions.

Sources#