Skip to content
ClapelloNotes by Barath
ReactCh 08 · 3/6
Core4 min readUpdated

React / 42

The lifecycle: mount, update, unmount

TL;DR

A class component is born, changes and dies. React calls a method at each stage, split into a pure render phase and a commit phase where side effects belong.

Three stages, two phases

Every component goes through up to three stages:

  • Mounting: it appears on the page for the first time.
  • Updating: it re-renders because its props or state changed.
  • Unmounting: it's removed from the page.

Inside each stage, React works in two phases:

  • Render phase: React calls render() to work out what the UI should be. This must be pure (no side effects), because React may pause it, throw it away, or, in Strict Mode, run it twice.
  • Commit phase: React applies the changes to the real DOM, then calls componentDidMount or componentDidUpdate. The DOM is ready, so side effects belong here.

Mount

first time it appears

render phase · pure

  1. constructor()
  2. getDerivedStateFromProps()(rare)
  3. render()
React inserts the DOM

commit phase · side effects ok

  1. componentDidMount()

Update

new props · setState · forceUpdate

render phase · pure

  1. shouldComponentUpdate()(rare)
  2. render()
React patches the DOM

commit phase · side effects ok

  1. getSnapshotBeforeUpdate()(rare)
  2. componentDidUpdate(prevProps, prevState)

Unmount

parent stops rendering it

render phase · pure

  1. (nothing runs on it)
just before removal

commit phase · side effects ok

  1. componentWillUnmount()
Render phase: work out the UI. It must be pure, because React may pause, redo or (in Strict Mode) double it. Commit phase: the DOM is real, so side effects go here.

Mount and update: fetch data

componentDidMount runs once, after the first render is in the DOM: the classic place to load data. componentDidUpdate(prevProps, prevState) runs after every re-render except the first, and tells you what the props and state were before, so you can react only to real changes.

UserCard.jsx
import { Component } from "react";
 
class UserCard extends Component {
  state = { user: null };
 
  componentDidMount() {
    this.loadUser();
  }
 
  componentDidUpdate(prevProps) {
    if (prevProps.userId !== this.props.userId) {
      this.loadUser(); // only when the id actually changed
    }
  }
 
  async loadUser() {
    const id = this.props.userId;
    const res = await fetch(`https://dummyjson.com/users/${id}`);
    const user = await res.json();
    if (id === this.props.userId) this.setState({ user }); // ignore stale replies
  }
 
  render() {
    const { user } = this.state;
    return <p>{user ? `${user.firstName} ${user.lastName}` : "Loading…"}</p>;
  }
}

Notice the two guards. The if in componentDidUpdate stops a loop: setState causes an update, which calls componentDidUpdate again. The check in loadUser stops a race: if userId changes quickly, an older, slower reply must not overwrite the newer one.

Unmount: clean up after yourself

componentWillUnmount runs just before the component is removed. Its job is to undo whatever componentDidMount started.

Clock.jsx
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>;
  }
}

Without clearInterval, the timer keeps firing every second after the clock is gone, and each time the clock mounts again (say, every visit to that page) you start another one. That's a leak: work and memory nobody needs. The same goes for window.addEventListener (pair it with removeEventListener), WebSocket connections and subscriptions.

Don't

Side effects in render

render() {
  fetch("/api/menu"); // runs on every render
  return <Menu />;
}

Do

Side effects in the commit phase

componentDidMount() {
  fetch("/api/menu")
    .then((r) => r.json())
    .then((menu) => this.setState({ menu }));
}

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.