Order of componentDidMount in React components hierarchy
Asked Answered
D

3

12

I have an React application that has the following structure:

component A is composed of B and C

When the component B calls it's componentDidMount method, is this true that all component finished mounting?

Or in other words does React fire componentDidMount after all components in the tree were mounted?

or e.g. Components B componentDidMount is called when component A mounted?

Dyandyana answered 18/1, 2018 at 14:36 Comment(0)
D
19

According to the documentation, the order of the lifecycle methods on first mount is as follows:

  1. constructor()
  2. componentWillMount()
  3. render()
  4. componentDidMount()

Let's say you have this component:

class A extends Component {
  render() {
    return (
      <div>
        <B />
        <C />
      </div>
    )
  }
}

When A is mounted, it will fire componentDidMount(). That will happen after render. Since B and C do not exist before A's render() is called, the completion of A's mounting requires that B and C finish their respective lifecycles. A's componentDidMount() will fire after B and C are mounted. A's componentWillMount() fires before A's render(), and therefore it also fires before B or C are mounted

UPDATE

As of React 16.3, componentWillMount starts the deprecation process, along with componentWillUpdate and componentWillReceiveProps. The above example will work fine in any 16.x release of react, but it will get deprecation warnings. There are new methods that take place of the deprecated ones, with their own lifecycle. More about them in the component API docs. Here is a cheatsheet diagram for the new lifecycles

Dunkin answered 18/1, 2018 at 15:33 Comment(3)
componentDidMount is not being deprecated.Merriemerrielle
@Merriemerrielle oh yeah, it was a typo lol, I meant to write componentWillMountDunkin
Cheat sheet diagram attached to this answer is very useful for all the developers out there, no matter the level - beginner, average or advanced etc. Highly recommended. Thanks for sharing.Sleuth
E
2

Parent's componentDidMount fires after children's.

Similar issue: In which order are parent-child components rendered?

Erving answered 28/11, 2019 at 17:39 Comment(0)
R
0

The React docs state:

componentWillMount() is invoked immediately before mounting occurs. It is called before render()...

Each component will fire its own componentDidMount. A will its own, then B, then C.

So I guess the answer to your question is, no, not all components would have finished mounting, s they fire the life cycle method 'immediately before mounting'.

Ryals answered 18/1, 2018 at 14:42 Comment(1)
You used componentWillMount() description in answer to question about componentDidMount()... It's contradictive!Duckbill

© 2022 - 2024 — McMap. All rights reserved.