ama icon indicating copy to clipboard operation
ama copied to clipboard

On React's async setState

Open tp opened this issue 9 years ago • 0 comments

Given that there "is no guarantee of synchronous operation of calls to setState", is it possible that the two counters in the following example would diverge on very rapid (or automatically triggered) clicks?

let actual_clicks = 0;

class StateCounterTest extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      counter: 0,
    };

    this._incCounter = () => {
      actual_clicks++;
      this.setState({
        counter: this.state.counter + 1,
      });
    }
  }

  render () {
    return <button onClick={this._incCounter}>{this.state.counter}</button>;
  }
}

My understanding is, that there is no guarantee that actual_clicks always equals this.state.counter it the state update is implemented like above.

Is this understanding correct?

tp avatar Jul 19 '16 15:07 tp