When state is not updated setState callback should not be invoked
See original GitHub issueDo you want to request a feature or report a bug? Feature
What is the current behavior?
When null is returned in setState updater, callback is invoked.
this.setState((prevState) => null, callback);
Example (see console):
https://stackblitz.com/edit/set-state-callback
What is the expected behavior? When state is not updated callback should not be invoked.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? ^16.0.0
What do you think about it? First of all we can consider callback what invokes after every setState. On the other side we can consider it as callback invoked only after state change. In my opinion second option is more handy because if I want to invoke callback with some job, I usually need to do something when state changed.
Issue Analytics
- State:
- Created 4 years ago
- Reactions:1
- Comments:5 (1 by maintainers)
In general we recommend to avoid
setState
callback because it makes it too easy to write code that behaves inconsistently depending on where the update happens. Try to prefercomponentDidUpdate
if you can.We don’t plan to change the
setState
callback semantics at this point.I believe this is more related to how you implement the setState and it’s not necessary to add feature to setState method. But for your problem you have two solutions.
Solution 1 You can ensure this.setState doesn’t execute when you have values like null or undefined by evaluating and checking the value you are going to update.
Solution 2 You can use LifeCycle method componentDidUpdate which is invoked only when there is change in state or props.