0
//Example #1 - I KNOW THIS IS WRONG
this.state.myCount = this.state.myCount + 42;

//Example #2 - Why is this wrong ?
this.setState({
    myCount: this.state.myCount + 42, 
})

//Example #3 - proper way, as per React docs 
this.setState( (prevState, props) => ({
  myCount: prevState.myCount + 42
}));

Now I've been using Example#2 without ever encountering an error in 3+ years of doing React.

Why is Example#2 wrong, can someone give a counter example, that will actually display an error in the console?

joedotnot
  • 4,810
  • 8
  • 59
  • 91
  • Example 2 -> [This is what react docs say about it](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous). There is a chance that the state value may not be the latest. There will not be any console error, based on some scenarios you may not get the latest state value – kiranvj Oct 25 '20 at 16:06
  • @Kiranvj yes that's exactly the same place where I read today it is wrong, but as I said, if it is so wrong show me a counter example, before I go change all my code everywhere. – joedotnot Oct 25 '20 at 16:12
  • A counter example will always. To get the inconsistent behavior it should be checked with a scenario that involves multiple concurrent props and state changes. – kiranvj Oct 25 '20 at 16:16
  • Not only in the concurrent scenarios but any time when you need to memoize something ( function, values, ...). – David Galoyan Oct 25 '20 at 16:20

1 Answers1

0

Example from this post from Medium and solution from post Why is setState in reactjs Async instead of Sync?

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

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

in the article they claim:

There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

Kakiz
  • 1,145
  • 1
  • 9
  • 18