Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 132 ยท Components and Props

Class Components and the Lifecycle

Read and migrate legacy React class components - state, setState, componentDidMount, componentDidUpdate, componentWillUnmount and how each one maps to hooks, with runnable examples.

Every React lesson on this site uses function components and hooks, and that is what you should write today. But React has existed since 2013, and hooks arrived in 2019. Millions of lines of production code, many open-source libraries and plenty of older tutorials still use class components. Sooner or later you will open a file that says class Profile extends Component and need to read it, fix a bug in it, or migrate it.

This lesson is a field guide to that old style. You will see how a class holds state, what the lifecycle methods do and when React calls them, how each one maps onto a hook, and which jobs still need a class (hint: one). Class components are not deprecated and still work in React 19, so you can run every example below in the editor.

Anatomy of a class component

A class component extends Component and must have a render() method that returns JSX. Props arrive as this.props. State lives in this.state and is changed with this.setState.

A class component with state

Compare it with the function version you know from useState: the state object, the handler and the JSX are all the same ideas, just spread across this. Three details cause most class bugs:

  • this binding. A method passed as onClick={this.increment} loses its this unless it is an arrow-function class field (as above) or is bound in the constructor. Forgetting this gives the famous Cannot read properties of undefined (reading 'setState').
  • setState merges. Calling this.setState({ count: 1 }) updates only count and keeps other keys in this.state. The useState setter does the opposite: it replaces the value completely.
  • One state object per component. A class has a single this.state, so unrelated values (a timer, a form field, a flag) sit side by side, and the code that deals with one concern is scattered across several lifecycle methods.

As with hooks, state updates are batched and this.state is a snapshot for the current render, so use the updater form this.setState((previous) => ...) when the new value depends on the old one. See how state updates work.

The three phases of a lifecycle

A component instance is mounted (created and inserted into the page), updated any number of times (new props or new state), and finally unmounted (removed). Class components expose a method for each moment.

stateDiagram-v2
    [*] --> Mounting
    Mounting: Mounting<br/>constructor, render
    Mounting --> Mounted: DOM ready, componentDidMount
    Mounted --> Updating: new props or setState
    Updating: Updating<br/>render
    Updating --> Mounted: DOM updated, componentDidUpdate
    Mounted --> [*]: componentWillUnmount

A class component's life: mount once, update many times, unmount once. The "Did" methods run after React has changed the page.

  • render() runs on mount and on every update. It must be pure, exactly like a function component's body (see keeping components pure): no timers, no fetches, no setState.
  • componentDidMount() runs once, after the first render has reached the DOM. This is the place for starting a fetch, adding an event listener or opening a subscription.
  • componentDidUpdate(prevProps, prevState) runs after every update except the first render. You compare the previous values with the current ones to decide whether something changed.
  • componentWillUnmount() runs just before the component is removed. You undo whatever componentDidMount started.

Watch the order in the console as you click and toggle.

Logging every lifecycle method

On load the console shows render: count = 0 and then componentDidMount. Each click on the counter logs render: count = 1 and then componentDidUpdate: count 0 -> 1. Pressing "Hide" logs componentWillUnmount, and "Show" starts again with a brand-new instance, so the count is back at 0. Notice that render always runs before the "Did" method: those methods are for what happens after the screen is updated.

Mapping lifecycle methods to hooks

Hooks reorganise the same moments around what you are synchronising instead of when it happens. The closest translation looks like this:

Class Function component
this.state + this.setState useState / useReducer
constructor setting initial state useState(initialValue) or a lazy initializer
render() the function body
componentDidMount useEffect(() => { ... }, [])
componentDidUpdate (when a value changed) useEffect(() => { ... }, [value])
componentWillUnmount the cleanup function returned by an effect
shouldComponentUpdate / PureComponent memo
this.myField = ... (instance field) useRef
static contextType / Context.Consumer useContext (context)

The table hides a difference in thinking. In a class, a subscription that depends on a prop needs three methods: componentDidMount to subscribe, componentDidUpdate to notice the prop changed, unsubscribe from the old value and subscribe to the new one, and componentWillUnmount to unsubscribe. With hooks, one effect with its cleanup describes the same thing once, and effect dependencies decide when it re-runs. Here are both side by side, listening to the same tiny publish and subscribe channel.

The same subscription as a class and as a hook

Press "Publish to news": both receivers update. Press "Switch channel": each logs an unsubscribe news followed by subscribe sports, and publishing now reaches both again on the new channel. The class needed an if that compares prevProps.channel with this.props.channel, and a hand-written copy of the subscribe call. If you forget the if, the component resubscribes after every update, including its own setState. The hook's dependency array makes that mistake much harder.

Other class methods you will meet

  • constructor(props) with super(props) used to set this.state and bind methods. Class fields (state = {...} and arrow methods) replace it in modern code.
  • shouldComponentUpdate(nextProps, nextState) returns false to skip a render, and PureComponent does a shallow comparison for you. The function equivalent is memo.
  • getSnapshotBeforeUpdate reads the DOM (for example a scroll position) just before React changes it, then passes the value to componentDidUpdate. There is no hook for it; the closest tool is a layout effect.
  • componentWillMount, componentWillReceiveProps and componentWillUpdate are the legacy "will" methods. They were unsafe with concurrent rendering, so they were renamed with an UNSAFE_ prefix and should be rewritten. Derived values belong in the render body, and resets belong in a key (see state and keys).
  • Error boundaries. static getDerivedStateFromError and componentDidCatch have no hook equivalent. This is the one job that still requires a class; see error boundaries.

Every lifecycle method, one by one

The short list above is enough for most work. Old codebases and interviews, though, go through all the methods, so here they are in the order React calls them.

Phase Method Runs Typical use
Mount constructor(props) once, first Initialize state (today: class fields)
Mount, update static getDerivedStateFromProps(props, state) before every render Copy a prop into state (rare, see below)
Mount, update render() every render Return JSX; must be pure
Mount componentDidMount() once, after the first DOM commit Fetch, subscribe, measure
Update shouldComponentUpdate(nextProps, nextState) before re-render Return false to skip the render
Update getSnapshotBeforeUpdate(prevProps, prevState) after render, before the DOM changes Read scroll position or size
Update componentDidUpdate(prevProps, prevState, snapshot) after the DOM changed React to changes, fetch on prop change
Unmount componentWillUnmount() once, before removal Clean up timers and subscriptions
Error static getDerivedStateFromError(error) and componentDidCatch(error, info) when a descendant throws Show a fallback, report the error

Run the next example and read the console: it logs each method as React calls it, for a mount, a state update, a prop update, and an unmount.

The class lifecycle in call order

Click the probe's own button: you get getDerivedStateFromProps, shouldComponentUpdate -> true, render, getSnapshotBeforeUpdate, componentDidUpdate. Click Re-render parent only: the parent renders again, but shouldComponentUpdate returns false (nothing the probe uses changed), so render and the rest do not run. That is exactly the saving PureComponent and memo give you.

getDerivedStateFromProps

This static method runs before every render, on mounts and on updates (since React 16.4, also on setState). It receives the next props and the current state and returns an object to merge into state, or null. It has no this, on purpose, so you cannot cause side effects in it. Its only legitimate job is to keep some state in step with a prop, for example resetting an edit buffer when the record being edited changes:

JSX
// read-only
class EmailEditor extends Component {
  state = { draft: this.props.email, lastEmail: this.props.email };

  static getDerivedStateFromProps(props, state) {
    if (props.email !== state.lastEmail) {
      return { draft: props.email, lastEmail: props.email }; // reset when the prop changes
    }
    return null;
  }
  // ...
}

The React team's advice is to avoid it: copying props into state creates two sources of truth. Prefer a fully controlled component, or a fully uncontrolled one with a key so React resets it for a new record: <EmailEditor key={user.id} email={user.email} />. The same reset in a function component is a key too.

getSnapshotBeforeUpdate

It runs after render but before React writes changes to the DOM, so you can still read the old layout. The classic use is keeping a chat scrolled to the same place when messages are added above. The value you return arrives as the third argument of componentDidUpdate:

JSX
// read-only
getSnapshotBeforeUpdate(prevProps) {
  if (prevProps.messages.length < this.props.messages.length) {
    const list = this.listRef.current;
    return list.scrollHeight - list.scrollTop;   // distance from the bottom, before the change
  }
  return null;
}

componentDidUpdate(prevProps, prevState, snapshot) {
  if (snapshot !== null) {
    const list = this.listRef.current;
    list.scrollTop = list.scrollHeight - snapshot; // restore it after the change
  }
}

The legacy "will" methods

Before React 16.3 there were componentWillMount, componentWillReceiveProps and componentWillUpdate. With concurrent rendering, React may start a render and throw it away, so a method that ran before the render could run twice or run for a render that never reached the screen, which made side effects in them buggy. They were renamed UNSAFE_componentWillMount and so on, warn in strict mode, and should be migrated:

Old method What it was used for Modern replacement
componentWillMount Setting initial state, fetching Constructor or class field for state; componentDidMount for fetching
componentWillReceiveProps(nextProps) Reacting to prop changes, resetting state componentDidUpdate for side effects; key or getDerivedStateFromProps for resets
componentWillUpdate Reading the DOM before an update getSnapshotBeforeUpdate

In hooks there is no equivalent of "will mount": code in the function body runs during render, and anything with an effect belongs in useEffect, after the render has reached the screen. If you want something to happen before the first paint, use useLayoutEffect.

componentDidCatch

When any descendant throws while rendering, a class with getDerivedStateFromError (to switch to a fallback UI) and componentDidCatch(error, info) (to log info.componentStack) acts as an error boundary. It is the one lifecycle job with no hook, as shown in Error Boundaries.

Converting a function component to a class (and back)

You will sometimes be asked to convert in either direction, so know the translation. A function component becomes a class by moving its body into render(), props to this.props, each useState to one field of this.state (updated with this.setState, which merges, unlike a state setter that replaces), and each useEffect into componentDidMount / componentDidUpdate / componentWillUnmount:

JSX
// function
function Counter({ step }) {
  const [count, setCount] = useState(0);
  useEffect(() => { document.title = 'Count ' + count; }, [count]);
  return <button onClick={() => setCount(count + step)}>{count}</button>;
}

// class
class Counter extends Component {
  state = { count: 0 };
  componentDidMount() { document.title = 'Count ' + this.state.count; }
  componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) document.title = 'Count ' + this.state.count;
  }
  render() {
    return <button onClick={() => this.setState({ count: this.state.count + this.props.step })}>{this.state.count}</button>;
  }
}

Notice that one useEffect became two methods, and that the if in componentDidUpdate is the hand-written dependency array. Going the other way (class to function) is the migration path described below.

Should you migrate?

Not automatically. A working class component is not a bug, and a rewrite risks new ones. A sensible policy is: write all new components as functions, keep stable classes as they are, and convert a class when you are already changing it for another reason. When you do convert:

  1. List what the class does in each lifecycle method and group it by purpose (subscription, document title, data loading), not by method name.
  2. Turn each purpose into one useEffect with its cleanup, and put the values it reads in the dependency array.
  3. Replace this.state fields with one useState per independent value, and this.timer-style instance fields with refs.
  4. Extract repeated purposes into custom hooks, which classes never had a good way to share.

Libraries that give you a class-only API (a few older HOCs or boundary helpers) can still be used from function components by wrapping them. You cannot use hooks inside a class, but a class can render a function component, and the reverse is just as valid.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which lifecycle method runs once, right after the component's first render has reached the DOM?

    componentDidMount runs a single time after the first render. It is where classes start fetches, listeners and subscriptions.
  2. 2. What does this.setState({ count: 1 }) do to the other keys in this.state?

    Class setState does a shallow merge. The useState setter is different: it replaces the whole value.
  3. 3. Which hook code corresponds to componentDidMount plus componentWillUnmount for a subscription that never changes?

    An effect with an empty dependency array runs after the first render, and the function it returns is the cleanup that plays the role of componentWillUnmount.
  4. 4. Why does a class need an if (prevProps.channel !== this.props.channel) check inside componentDidUpdate?

    componentDidUpdate runs after every update caused by props or state. The comparison restricts the work to the case you care about. A hook's dependency array does this for you.
  5. 5. Which task can still only be done with a class component?

    getDerivedStateFromError and componentDidCatch exist only on classes. Everything else has a function and hook equivalent.

Summary

  • A class component extends Component, reads props from this.props, keeps state in this.state, changes it with this.setState (which merges) and describes the UI in render().
  • The lifecycle has three phases: mount (componentDidMount), update (componentDidUpdate) and unmount (componentWillUnmount). The "Did" methods run after the DOM has changed.
  • In a function component, useState replaces this.state, an effect with a cleanup replaces the three lifecycle methods for one concern, memo replaces PureComponent and refs replace instance fields.
  • Watch out for this binding, forgotten prevProps comparisons and the unsafe componentWill* methods when reading legacy code.
  • Classes are not deprecated. Write new code with functions, migrate old classes gradually, and keep a class only for an error boundary.

Next: Handling Events