Think of a component that has a prop 'name' and state 'elapse'.
new Component(name) => "Hi {name}. It's been {elapse} seconds"
{elapse}
should be reset to 0 when the prop {name}
changes.
If the prop changes from 'Alice' to 'Bob' at 10 seconds, the message should change from
Hi Alice. It's been 10 seconds
to
Hi Bob. It's been 0 seconds
getDerivedStateFromProps
cannot be used because {elapse}
is not a pure function of {name}
, and I cannot return 0 because it may be called on re-render.
componentDidUpdate
will eventually update {elapse}
to 0, but before that, the invalid state "Hi Bob. It's been 0 seconds" is shown to the user.
Can getDerivedStateFromProps
or componentDidUpdate
implement this scenario?
In many cases the state is not a pure function of props. Is getDerivedStateFromProps
only for stateless functional components? Does react encourage the use of stateless components?
How can getDerivedStateFromProps
replace componentWillReceiveProps
in stateful components?
In React class components, we had the componentDidUpdate method, which provided the previous prop and state arguments. Now, with functional components, we have effects. In order to accomplish saving the previous state and prop values, we can store them to a ref.
There are a few life cycle methods that have been deprecated and renamed in React 17. We don't need to use these anymore— getDerivedStateFromProps and getSnapshotBeforeUpdate essentially replaced them.
ReactJS – getDerivedStateFromProps() MethodThis method is majorly used to update the state, before the rendering of the component, which depends upon the props received by the component. This method is called on every rerendering of the component.
The useEffect hook is also the equivalent of the componentWillReceiveProps or componentDidUpdate hooks. All we have to do is to pass in an array with the value that we want to watch for changes.
If you look around you'll see you're not the first one having this problem - it was thoroughly discussed on github 1 2 3 and in a thread on hackernews here. The recommended solution is to mirror the props you need to check in the state:
state = { name: "", lastTime: Date.now() }
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.name !== prevState.name) {
return { name: nextProps.name, lastTime: Date.now() };
}
return null;
}
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