Created
June 30, 2016 16:43
-
-
Save jjsub/bae083b2ec2d7805eda1aa348a2b4d8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setState is Asynchronous | |
I didn’t notice this when I started out with React. The setState function is asynchronous! | |
If you call setState and immediately inspect this.state, chances are it will not be updated yet. | |
If you need to set the state and immediately act on that change, you can pass in a callback function like this: | |
this.setState({name: 'Joe'}, function() { | |
// called after state has been updated | |
// and the component has been re-rendered | |
}); | |
Another alternative is to use the componentWillUpdate or componentDidUpdate lifecycle hooks, which will be called | |
immediately before and after rendering in response to your state change. | |
They’ll also get called whenever props change – so if you absolutely want to respond only to state changes, | |
use the callback approach. | |
from: | |
https://daveceddia.com/react-gotchas/?utm_campaign=0630gotchas |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment