Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence of componentWillMount calls in React.js

According to this page http://busypeoples.github.io/post/react-component-lifecycle/ The render method for a component is called right in between the componentWillMount and componentDidMount methods amongst other places.

But the react.js documentation for component lifecycles here https://facebook.github.io/react/docs/component-specs.html says that the componentDidMount methods of all child activities are called before the parent. I can understand that componentDidMount is ok to call after any child components are rendered but how does the runtime know which children to call the componentWillMount function on before they are rendered? Or am I right in assuming that componentWillMount is called for the parent activity first and then for the children (unlike componentDidMount)?

Thanks!

like image 611
Curious Avatar asked May 09 '16 16:05

Curious


People also ask

How many times componentWillMount is called?

Your component will get unmounted every time you change route, and a new one will be mounted when you change back.

Which is called first componentDidMount or componentWillMount?

componentDidMount() is only called once, on the client, compared to componentWillMount() which is called twice, once to the server and once on the client. It is called after the initial render when the client received data from the server and before the data is displayed in the browser.

Is componentWillMount called before render?

Using componentWillMount() to Manipulate State As you know, the life-cycle hook componentWillMount triggers before the initial render, and the function will only trigger once in the lifespan of a component. It is used to update the state value before the DOM is rendered, creating a state variable, as shown below.


1 Answers

OK. so here goes. If you have a simple structure with a parent and 2 children like this:

<Parent>
  <Child/>
  <Child/>
</Parent>

Then the sequence of events firing will be:

  1. <Parent> componentWillMount()
  2. <Parent> render(), which starts to render children
  3. <Child> componentWillMount() of the first child
  4. <Child> render() of the first child
  5. <Child> componentWillMount() of the second child
  6. <Child> render() of the second child
  7. <Child> componentDidMount() of the first child (these will start only after the last render in the tree has run)
  8. <Child> componentDidMount() of the second child
  9. <Parent> componentDidMount() (this one will run only after its last child has run componentDidMount)

You can find a codepen example here.

like image 79
wintvelt Avatar answered Oct 21 '22 04:10

wintvelt