Skip to content

Instantly share code, notes, and snippets.

@Goloburda
Created December 18, 2019 10:47
Show Gist options
  • Save Goloburda/d634172dbbe8959c5ec6875dd92d4484 to your computer and use it in GitHub Desktop.
Save Goloburda/d634172dbbe8959c5ec6875dd92d4484 to your computer and use it in GitHub Desktop.
React setState
/*
The setState() method does not immediately update the state of the component,
it just puts the update in a queue to be processed later.
React may batch multiple update requests together to make rendering more efficient.
Due to this, special precautions must be made when you try to update
the state based on the component's previous state.
*/
state = { count: 1 };
componentDidMount() {
// this.setState({ count: this.state.count + 1 });
// this.setState({ count: this.state.count + 1 });
// this.setState({ count: this.state.count + 1 });
// count = 1;
/*
Object.assign(
{},
{ count: this.state.count + 1 },
{ count: this.state.count + 1 },
{ count: this.state.count + 1 },
)
*/
this.setState(prevState => ({ count: prevState.count + 1 }));
this.setState(prevState => ({ count: prevState.count + 1 }));
this.setState(prevState => ({ count: prevState.count + 1 }));
//count = 4
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment