React / 42
The lifecycle: mount, update, unmount
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
componentDidMountorcomponentDidUpdate. The DOM is ready, so side effects belong here.
Mount
first time it appears
render phase · pure
- constructor()
- getDerivedStateFromProps()(rare)
- render()
commit phase · side effects ok
- componentDidMount()
Update
new props · setState · forceUpdate
render phase · pure
- shouldComponentUpdate()(rare)
- render()
commit phase · side effects ok
- getSnapshotBeforeUpdate()(rare)
- componentDidUpdate(prevProps, prevState)
Unmount
parent stops rendering it
render phase · pure
- (nothing runs on it)
commit phase · side effects ok
- componentWillUnmount()
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.
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.
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.
