When value is assigned to components state, why console.log prints the previous state?
From the docs:
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 to print the change after a call to setState
, use the optional callback parameter:
this.setState({
number: num
}, function () {
console.log(this.state.number);
});
The setState method is asynchronous, so the new state is not there yet on console.log call. You can pass a callback as a second parameter to setState and call console.log there. In this case the value will be correct.