Why use getDerivedStateFromProps when you have componentDidUpdate?
From this article:
As
componentWillReceiveProps
gets 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
getDerivedStateFromProps
andcomponentWillReceiveProps
onlygetDerivedStateFromProps
will 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
componentDidUpdate
instead.
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
.