So Dan Abramov answered on Twitter and it seems like there are 2 reasons why you should use getDerivedStateFromProps instead of componentDidUpdate + setState:
setState in componentDidUpdate causes an extra render (not directly perceptible to user but it slows down your app). And your render method can’t assume the state is ready (because it won’t be the first time).
- Performance reason: it avoids unnecessary re-render.
- As
getDerivedStateFromPropsis called before rendering on init, you can initialise your state in this function instead of having a constructor to do so. Currently you had to have a constructor orcomponentWillMountto init your state before initial rendering.
How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps
Why use getDerivedStateFromProps when you have componentDidUpdate?
Newest 'getderivedstatefromprops' Questions - Stack Overflow
componentWillReceiveProps vs getDerivedStateFromProps
Is componentDidUpdate deprecated?
What is the difference between componentDidUpdate and componentDidMount?
What to use instead of componentWillReceiveProps?
Videos
So Dan Abramov answered on Twitter and it seems like there are 2 reasons why you should use getDerivedStateFromProps instead of componentDidUpdate + setState:
setState in componentDidUpdate causes an extra render (not directly perceptible to user but it slows down your app). And your render method can’t assume the state is ready (because it won’t be the first time).
- Performance reason: it avoids unnecessary re-render.
- As
getDerivedStateFromPropsis called before rendering on init, you can initialise your state in this function instead of having a constructor to do so. Currently you had to have a constructor orcomponentWillMountto init your state before initial rendering.
getDerivedStateFromProps is actually replacement for componentWillReceiveProps and componentDidMount is not going to be deprecated.
I'm pretty sure it was the community that decided to make a static method with that name.
The reason for this change is that componentWillReceiveProps was one of the methods that led to confusion and further to some memory leaks in user applications:
Many of these issues are exacerbated by a subset of the component lifecycles (componentWillMount, componentWillReceiveProps, and componentWillUpdate). These also happen to be the lifecycles that cause the most confusion within the React community. For these reasons, we are going to deprecate those methods in favor of better alternatives.
Here's the Dan Abramov tweet that also makes this more clear:
However, this means that we’ll part our ways with componentWillReceiveProps() in 17. We think getDerivedStateFromProps() does the same job better and is less confusing. It also happens that cWRP() really messes up our plans for data fetching features that might be in pipeline.
About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.
In case you really need the old value of a prop, you can always cache it in your state with something like this:
state = {
cachedSomeProp: null
// ... rest of initial state
};
static getDerivedStateFromProps(nextProps, prevState) {
// do things with nextProps.someProp and prevState.cachedSomeProp
return {
cachedSomeProp: nextProps.someProp,
// ... other derived state properties
};
}
Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.
UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.
As we recently posted on the React blog, in the vast majority of cases you don't need getDerivedStateFromProps at all.
If you just want to compute some derived data, either:
- Do it right inside
render - Or, if re-calculating it is expensive, use a memoization helper like
memoize-one.
Here's the simplest "after" example:
import memoize from "memoize-one";
class ExampleComponent extends React.Component {
getDerivedData = memoize(computeDerivedState);
render() {
const derivedData = this.getDerivedData(this.props.someValue);
// ...
}
}
Check out this section of the blog post to learn more.
From this article:
As
componentWillReceivePropsgets removed, we need some means of updating the state based on props change — the community decided to introduce a new — static — method to handle this.What’s a static method? A static method is a method / function that exists on the class not its instance. The easiest difference to think about is that static method does not have access to this and has the keyword static in front of it.
Ok, but if the function has no access to this how are we to call this.setState? The answer is — we don’t. Instead the function should return the updated state data, or null if no update is needed
The returned value behaves similarly to current setState value — you only need to return the part of state that changes, all other values will be preserved.
You still need to declare the initial state of the component (either in constructor or as a class field).
getDerivedStateFromProps is called both on initial mounting and on re-rendering of the component, so you can use it instead of creating state based on props in constructor.
If you declare both
getDerivedStateFromPropsandcomponentWillReceivePropsonlygetDerivedStateFromPropswill be called, and you will see a warning in the console.Usually, you would use a callback to make sure some code is called when the state was actually updated — in this case, please use
componentDidUpdateinstead.
With componentDidUpdate you can execute callbacks and other code that depends on the state being updated.
getDerivedStateFromProps is a static function and so has no access to the this keyword. Also you wouldn't have any callbacks placed here as this is not an instance based lifecycle method. Additionally triggering state changes from here could cause loops(e.g. with redux calls).
They both serve different fundamental purposes. If it helps getDerivedStateFromProps is replacing componentWillReceiveProps.
getDerivedStateFromProps is not a direct alternative to componentWillReceiveProps, purely because of the fact that its called after every update, whether its the change in state or change in props or re-render of parent.
However whatever is the case, simply returning the state from getDerivedStateFromProps is not the right way, you need to compare the state and props before returning the value. Else with every update the state is getting reset to props and the cycle continues
As per the docs
getDerivedStateFromPropsis invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, ornullto update nothing.This method exists for rare use cases where the state depends on changes in props over time. For example, it might be handy for implementing a
<Transition>component that compares its previous and next children to decide which of them to animate in and out.Deriving state leads to verbose code and makes your components difficult to think about. Make sure you’re familiar with simpler alternatives:
If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use
componentDidUpdatelifecycle instead.If you want to re-compute some data only when a prop changes, use a
memoizationhelper instead.If you want to “reset” some state when a prop changes, consider either making a component
fully controlledorfully uncontrolled with a key instead.
P.S. Note that the arguments to getDerivedStateFromProps are props and state and not nextProps and prevProps
To get into more details,
In order to make changes based on props change, we need to store prevPropsState in state, in order to detect changes. A typical implementation would look like
static getDerivedStateFromProps(props, state) {
// Note we need to store prevPropsState to detect changes.
if (
props.myPropsState !== state.prevPropsState
) {
return {
prevPropsState: state.myState,
myState: props.myPropsState
};
}
return null;
}
Finally, I resolved my issue. It was a painful debugging:
// Child Component
// instead of this
// this.props.onMyDisptach([...myPropsState])
// dispatching true value since myPropsState contains only numbers
this.props.onMyDispatch([...myPropsState, true])
This is because, I have two conditions: 1) on checkbox change (component) 2) on reset button pressed (child component)
I was needing to reset the states when reset button is pressed. So, while dispatching state to the props for reset button, I used a boolean value to know it's a change from the reset. You may use anything you like but need to track that.
Now, here in the component, I found some hints to the differences between componentWillReceiveProps and getDerivedStateFromProps after debugging the console output.
// Component
static getDerivedStateFromProps(props, state) {
const { myPropsState: myState } = props
// if reset button is pressed
const true_myState = myState.some(id=>id===true)
// need to remove true value in the store
const filtered_myState = myState.filter(id=>id!==true)
if(true_myState) {
// we need to dispatch the changes to apply on its child component
// before we return the correct state
props.onMyDispatch([...filtered_myState])
return {
myState: filtered_myState
}
}
// obviously, we need to return null if no condition matches
return null
}
Here's what I found the results of the console output:
getDerivedStateFromProps logs immediately whenever props changes
componentWillReceiveProps logs only after child propagates props changes
getDerivedStateFromProps doesn't respond to the props changes ( I meant for the dispatch changes as in the example code)
componentWillReceiveProps responds to the props changes
Thus, we needed to supply the changes to child component while using getDerivedStateFromProps.
The process of pasting true value in the state I require because getDerivedStateFromProps handle all the changes unlike componentWillReceiveProps handles only the child component dispatches the changes to the props.
By the way, you may use custom property to check if it is changed and update the value if getDerivedStateFromProps but for some reason I have to tweak this technique.
There might be some confusion on my wording but I hope you'll get it.
You can use setStateinside componentDidUpdate. The problem is that somehow you are creating an infinite loop because there's no break condition.
Based on the fact that you need values that are provided by the browser once the component is rendered, I think your approach about using componentDidUpdate is correct, it just needs better handling of the condition that triggers the setState.
The componentDidUpdate signature is void::componentDidUpdate(previousProps, previousState). With this you will be able to test which props/state are dirty and call setState accordingly.
Example:
componentDidUpdate(previousProps, previousState) {
if (previousProps.data !== this.props.data) {
this.setState({/*....*/})
}
}
