When exactly is `componentDidMount` fired?
Inside a react component tree, componentDidMount()
is fired after all children components have also been mounted. This means, that any component's componentDidMount()
is fired before its parent has been mounted.
So if you want to measure DOM position and sizes etc, using componentDidMount()
of a child component is an unsafe place/ time to do this.
In your case: to get accurate reading from 100% width/height components, a safe place to take such measurements would be inside the componentDidMount()
of the top react component.
100% is a width/height relative to the parent/ container. So measurements can only be taken after the parent has been mounted too.
As you may know, componentDidMount
is triggered only once immediately after the initial rendering.
Since you are taking measurements, it would seem you would want to also trigger your measuring when componentDidUpdate
in case your measurements change when your component updates.
Please note that componentDidUpdate
does not occur for the initial render so you likely need both lifecycle events to trigger your measurement handling. See if this second event triggers for you and if it has different measurements.
In my opinion you should avoid using setTimeout
or requestAnimationFrame
when possible.
React Lifecycle Reference.
It is called only once when the component mounted. That’s the perfect time to do an asynchronous request to fetch data from an API. The fetched data would get stored in the internal component state to display it in the render() lifecycle method.
Simple: It Run After Render Functions