React / 43
Lifecycle order with parents and children
React renders a tree top-down, writes the DOM once, then runs didMount bottom-up. Knowing the exact order answers a classic interview question.
The setup
import { Component } from "react";
class Child extends Component {
constructor(props) {
super(props);
console.log(`${props.name} constructor`);
}
componentDidMount() {
console.log(`${this.props.name} didMount`);
}
render() {
console.log(`${this.props.name} render`);
return <li>{this.props.name}</li>;
}
}
class Parent extends Component {
// same three logs, labelled "Parent"
render() {
return (
<ul>
<Child name="Child A" />
<Child name="Child B" />
</ul>
);
}
}Mounting: down, then back up
Render phase ↓
parent first, then children in order
- 1Parent constructor · render
- 2Child A constructor · render
- 3Child B constructor · render
Commit phase ↑
DOM written, then children first
- 4Child A componentDidMount
- 5Child B componentDidMount
- 6Parent componentDidMount
Render phase, top-down
React creates and rendersParent, which returns twoChildelements. React then creates and renders each child in order. NodidMountyet, because nothing is in the DOM.One DOM write
With the whole tree worked out, React inserts all the DOM nodes in a single commit.Commit phase, bottom-up
componentDidMountruns for Child A, then Child B, then Parent last.
Children's didMount comes first because a parent is only "mounted" once everything inside it is. By the time Parent's componentDidMount runs, its children's DOM exists and their own didMount setup has finished.
Updating and unmounting
When the parent calls setState, the same shape repeats: render top-down (Parent, A, B), the DOM patch, then componentDidUpdate bottom-up (A, B, Parent).
Unmounting flips it. componentWillUnmount runs top-down: Parent first, then A, then B. Each component cleans up while its DOM is still attached.
Play with all three:
Parent with two children
Try it- console is empty, press Mount
| Stage | Order |
|---|---|
| Mount | P ctor → P render → A ctor → A render → B ctor → B render → A didMount → B didMount → P didMount |
| Update | P render → A render → B render → A didUpdate → B didUpdate → P didUpdate |
| Unmount | P willUnmount → A willUnmount → B willUnmount |
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.
