Reactjs-setState previous state is the first argument, props as the second argument

They say you should do like that instead of the below example.

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

They can’t assure the state will have the correct value if you access like this because setState() will happen asynchronously, other updates could occur and change the value. If you are going to calculate the state based on the previous state, you have to make sure you have the last and most up to date value, so they made setState() accept a function that is called with prevState and props, so you can have the correct value to update your state, like the example below.

 // Correct
this.setState((prevState, props) => ({
  counter: prevState.counter + props.increment
}));

Leave a Comment