Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

getDerivedStateFromProps is executed after setState #13015 #17701

Closed
vishalini253 opened this issue Dec 24, 2019 · 4 comments
Closed

getDerivedStateFromProps is executed after setState #13015 #17701

vishalini253 opened this issue Dec 24, 2019 · 4 comments

Comments

@vishalini253
Copy link

vishalini253 commented Dec 24, 2019

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

@zxh19890103
Copy link

zxh19890103 commented Dec 24, 2019

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.

@bvaughn
Copy link
Contributor

bvaughn commented Dec 25, 2019

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 😄

@vishalini253
Copy link
Author

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

@vishalini253
Copy link
Author

@bvaughn, Thanks for the answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants