In react a call to a component (R
) 's setState()
can trigger the re-render of all child components.
How can we know when that has finished ?
Which lifecycle method is called after all the children of R
have been mounted/rendered/updated ?
In more detail:
Let's consider the following situation:
There is a root component R
, and its child components C1
and C2
.
I would like to implement my own redux store where child components ( C1
and C2
) can dispatch actions and AFTER all the children have been mounted/re-rendered/updated I would like to command the redux store to process the dispatched actions.
So I would need to know when all children have been rendered and schedule a call to the redux store that will command the store to process the dispatched actions.
Which lifecycle method is called after R
's all children have been mounted/rendered/updated ?
The useEffect() hook is called when the component is mounted and sets the mounted. current value to true . The return function from the useEffect() hook is called when the component is unmounted and sets the mounted. current value to false .
render() Calling setState() here makes it possible for a component to produce infinite loops. The render() function should be pure, meaning that it does not modify a component's state. It returns the same result each time it's invoked, and it does not directly interact with the browser.
In Action. If we look at the gist below, this. setState() is used to change the name in componentWillMount() and componentDidMount() and the final name is reflected on the screen. An important thing to note here isthat as stated before, componentDidMount() occurs only once to give a render a second pass.
Yes. It calls the render() method every time we call setState only except when shouldComponentUpdate returns false .
Update: React has changed its lifecycle but in this case the method you need it's still the same. The new lifecycle is:
A) Mounting
B) Updating (includes both, props and state)
OLD ANSWER
ComponentDidUpdate
will do what you say. It is launched right after a render because of props changes or a render because of state changes.
Life Cycle:
A) Mounting
B) Props Changes
C) State Changes
More information: https://reactjs.org/docs/react-component.html#componentdidupdate
I think you are looking for the componentDidUpdate
lifecycle event. https://facebook.github.io/react/docs/react-component.html#componentdidupdate
It is triggered when the component is being updated (and that all its children are updated too).
⚠ this event is not triggered on the very first render. If you also need to handle to first render, you will have to use both componentDidUpdate
and componentDidMount
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With