gotchajavascriptreactCritical
Why does calling react setState method not mutate the state immediately?
Viewed 0 times
setstatemutatecallingwhyimmediatelythedoesreactmethodstate
Problem
I'm reading Forms section of reactjs documentation and just tried this code to demonstrate
When I update the `
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:
pending state transition. Accessing
method can potentially return the existing value. There is no
guarantee of synchronous operation of calls to
be batched for performance gains.
If you want a function to be executed after the state change occurs, pass it in as a callback.
setState() does not immediately mutate this.state but creates apending state transition. Accessing
this.state after calling thismethod can potentially return the existing value. There is no
guarantee of synchronous operation of calls to
setState and calls maybe 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.