React: getDerivedStateFromProps is executed after setState #13015

Created on 24 Dec 2019  ·  4Comments  ·  Source: facebook/react

Ideally getDerivedStateFromProps should not be called due to current component's setState. But it is behaving so. Can someone explain?

Couldn't find solution in #13015

Question

All 4 comments

setState will lead to re-render of component. For every render of component, getDerivedStateFromProps should be called. This is how getDerivedStateFromProps works.

What you should consider is how to return a partial state to merge.

Without example code, I don't understand what you're saying or asking.

It is expected that getDerivedStateFromProps would be called after a setState, since the state returned by getDerivedStateFromProps is based on both the current props and the previous state. So if the state has changed, (by a setState call), it's possible that the derived state may also have changed (since it is a combination of props and state).

We did not previously call it again if props didn't change, but that behavior caused problems and so we changed it (fixed it) in 16.4 as mentioned by this blog post:
https://reactjs.org/blog/2018/05/23/react-v-16-4.html#bugfix-for-getderivedstatefromprops

If you want to share some code and ask a specific question about why the method is run, one of us could take a look. For now though I'll assume your question has been answered :smile:

setState will lead to re-render of component. For every render of component, getDerivedStateFromProps should be called. This is how getDerivedStateFromProps works.

What you should consider is how to return a partial state to merge.

Thanks

@bvaughn, Thanks for the answer

Was this page helpful?
0 / 5 - 0 ratings