Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps

Tags:

reactjs

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?

like image 574
Karan Jariwala Avatar asked Apr 01 '18 15:04

Karan Jariwala


1 Answers

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.

like image 60
Shubham Khatri Avatar answered Sep 27 '22 23:09

Shubham Khatri