Skip to content

Instantly share code, notes, and snippets.

@jjsub
Created June 30, 2016 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjsub/bae083b2ec2d7805eda1aa348a2b4d8f to your computer and use it in GitHub Desktop.
Save jjsub/bae083b2ec2d7805eda1aa348a2b4d8f to your computer and use it in GitHub Desktop.
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