Robin Robin - 4 months ago 17
React JSX Question

Why can't we print the updated state right after state is updated by using setState()?

this.state = {term :1};

console.log("Before Update: "+this.state.term) //Before Update: 1

this.setState({term :this.state.term + 1});

console.log("After Update: "+this.state.term) //After Update: 1


What could be the reason for the same result before and after update?

Answer Source

this.setState method is asynchronous but you can call a function as second argument that trigger once when state is updated

this.setState({term :this.state.term + 1}, () => {
  console.log(this.state)
})