HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptreactCritical

Why does calling react setState method not mutate the state immediately?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
setstatemutatecallingwhyimmediatelythedoesreactmethodstate

Problem

I'm reading Forms section of reactjs documentation and just tried this code to demonstrate onChange usage (JSBIN).

var React= require('react');

var ControlledForm= React.createClass({
    getInitialState: function() {
        return {
            value: "initial value"
        };
    },

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

    },

    render: function() {
        return (
            
        );
    }
});

React.render(
    ,
  document.getElementById('mount')
);


When I update the ` value in the browser, the second console.log inside the handleChange callback prints the same value as the first console.log, Why I can't see the result of this.setState({value: event.target.value}) in the scope of handleChange` callback?

Solution

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);
});

Code Snippets

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

Context

Stack Overflow Q#30782948, score: 731

Revisions (0)

No revisions yet.