0

Please look into the following code. I have tried calling setState one below the other. It looks like count which is returned from the second call of setState is always set to this.state.count. Here, It's always assigned with 3

    class Counter extends React.Component {
    constructor(props){
        super(props);
        this.handleReset = this.handleReset.bind(this);
        this.state = {
            count : 0
        };
    }

    handleReset() {
        this.setState(() => {
            return {
                count: 1
            }
        });
        this.setState(() => {
            return {
                count: 3
            }
        });
    }
    render() {
        return (
            <div> 
                <h1>Count:{this.state.count}</h1>
                <button onClick={this.handleReset}>reset</button>
            </div>
        );
    }
  }
  ReactDOM.render(<Counter />, document.getElementById('app'));
Prem
  • 5,685
  • 15
  • 52
  • 95
  • 1
    check the [**doc**](https://reactjs.org/docs/react-component.html#setstate), and [this answer](https://stackoverflow.com/questions/42593202/why-calling-setstate-method-doesnt-mutate-the-state-immediately/42593250#42593250) – Mayank Shukla May 13 '18 at 19:08

2 Answers2

1

According to React docs, it can be async.

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state

(original source, and correct code example)

skiilaa
  • 1,212
  • 11
  • 20
0

setState is asynchronous. You can pass callback as second argument and see the updated state.

this.setState({ count: 5 }, () => {
  console.log(this.state.count) // 5
})
madox2
  • 49,493
  • 17
  • 99
  • 99
  • Then, why do I get the `this.state.count` always set to `3` which is returned from the second call for setState() api – Prem May 13 '18 at 19:07
  • @Prem because it was called last – madox2 May 13 '18 at 19:08
  • When two asynchronous calls are invoked one below the other, is there any guarantee for the order of execution? – Prem May 13 '18 at 19:10
  • 1
    @Prem, sure if you synchronously add it to the stack. But to be honest, I am not sure how react implements it – madox2 May 13 '18 at 19:18