gaearon / ama

Ask me anything!
222 stars 5 forks source link

On React's async setState #123

Open tp opened 8 years ago

tp commented 8 years ago

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?