Why calling react setState method doesn't mutate the state immediately? Why calling react setState method doesn't mutate the state immediately? reactjs reactjs

Why calling react setState method doesn't mutate the state immediately?


From React's documentation:

setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

If you want a function to be executed after the state change occurs, pass it in as a callback.

this.setState({value: event.target.value}, function () {    console.log(this.state.value);});


As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.

Michael Parker mentions passing a callback within the setState. Another way to handle the logic after state change is via the componentDidUpdate lifecycle method, which is the method recommended in React docs.

Generally we recommend using componentDidUpdate() for such logic instead.

This is particularly useful when there may be successive setStates fired, and you would like to fire the same function after every state change. Rather than adding a callback to each setState, you could place the function inside of the componentDidUpdate, with specific logic inside if necessary.

// examplecomponentDidUpdate(prevProps, prevState) {  if (this.state.value > prevState.value) {    this.foo();    }}


You could try using ES7 async/await. For instance using your example:

handleChange: async function(event) {    console.log(this.state.value);    await this.setState({value: event.target.value});    console.log(this.state.value);}