getDerivedStateFromProps is being added as a safer alternative to the legacy componentWillReceiveProps.
This is what the 16.3 doc says. Is there anything more to this lifecycle or is it just a name change?
getDerivedStateFromProps
is not just a name change to componentWillReceiveProps
. It's a static method that is called after a component is instantiated or before it receives new props, unlike componentWillReceiveProps
which was not called on initial render.
Return an object to update state in response to prop changes.
Return null to indicate no change to state.
Static lifecycle methods are introduced to prevent unsafe access of instance properties.
The purpose of getDerivedStateFromProps
is to only update the state based on props change and not take actions like API call or function call based on prevProps
that could be done. All of these could be done in the componentDidUpdate
lifecycle function which is safe because even if the change was done in componentWillReceiveProps
the data would arrive after render and most often you would trigger another re-render, which could well be done in the componentDidUpdate
lifecycle method.
You can refer to this RFC to understand more about why this change was made.
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