Do you want to request a feature or report a bug?
Bug
What is the current behavior?
Returning null
from getDerivedStateFromProps
triggers updates and componentDidUpdate
is being called.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:
https://jsfiddle.net/69z2wepo/328290/
What is the expected behavior?
componentDidUpdate
and render
methods should not be called.
componentDidUpdate
and render
methods should still be called because it was not blocked by shouldComponentUpdate
. Returning null
from getDerivedStateFromProps
will just not update the component's state.
https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops
But doesn't "update nothing" mean that there was no update and hence the corresponding lifecycle methods that happen after a state update shouldn't be called?
At the very least, the documentation should mention that this is intentional and "update nothing" doesn't mean that componentDidUpdate
and render
won't be called. It is very confusing when the method specifically asks us to return null
in case of no updates.
Send a pr to reactjs/reactjs.org changing the language to something like "or null to leave the state unchanged" :)
The state is left unchanged when you return null. The reason you return null, is that it's a clear signal to react that you intend to not update state, whereas undefined could indicate you do want to update but forgot to return anything. Components should continue to update tho as render may depend on new props even if state doesn't.
If you want to prevent updates shouldComponentUpdate is the hook for that.
Now I got the point irrespective of whether state updating or not updating only in shouldComponentUpdate() method we should check whether to invoke render method or not by returning true/false. But return statement of getDerivedStateFromProps doesn't affect on the render method .
correct me If I'm wrong.
Thanks.
@skirankumar7 Yes, getDerivedStateFromProps
is only ever called when a render is being triggered anyway, so it will never stop an impending render.
I think @jquense is spot on here. Using shouldComponentUpdate
to block a component update is the best approach. React can not know if the render
function is dependent on new props.
Thanks everyone for weighing in!
Most helpful comment
At the very least, the documentation should mention that this is intentional and "update nothing" doesn't mean that
componentDidUpdate
andrender
won't be called. It is very confusing when the method specifically asks us to returnnull
in case of no updates.