Passing a function to setState

Here’s the dirty secret about setState — it’s actually asynchronous.
React batches state changes for performance reasons, so the state may not change immediately after setState is called.
That means you should not rely on the current state when calling setState — since you can’t be sure what that state will be!
Here’s the solution — pass a function to setState, with the previous state as an argument.
Doing so avoids issues with the user getting the old state value on access (due to the asynchrony of setState)

Problem

  1. // assuming this.state.count === 0
  2. this.setState({count: this.state.count + 1});
  3. this.setState({count: this.state.count + 1});
  4. this.setState({count: this.state.count + 1});
  5. // this.state.count === 1, not 3

Solution

  1. this.setState((prevState, props) => ({
  2. count: prevState.count + props.increment
  3. }));

Variations

  1. // Passing object
  2. this.setState({ expanded: !this.state.expanded });
  3. // Passing function
  4. this.setState(prevState => ({ expanded: !prevState.expanded }));