Vishnu Paspunoor Vishnu Paspunoor - 2 months ago 7
React JSX Question

What happens when we use this.setState() in ReactJS?

I am confused about when the state actually changes when this.setState() is used in React. Here is my JSX:

var Hello = React.createClass({
getInitialState: function () {
return {
iterator: 0
}
},
handleClick: function () {
console.log(this.state.iterator);
this.setState({
iterator: this.state.iterator + 1
})
console.log(this.state.iterator)
},
render: function () {
return <button onClick={this.handleClick}>{this.state.iterator}</button>;
}
});

ReactDOM.render(
<Hello name="World"/>,
document.getElementById('container')
);


As you can see, I am logging the state of iterator before and after this.setState() is called. But both the times, it is logging the same number. After the first time I click the button, I was expecting to log 0 and 1 respectively but they both log 0 and 0. And on second click, they log 1 and 1. So when is the state actually getting changed and what exactly is happening here?

Answer

Citing https://facebook.github.io/react/docs/component-api.html

Notes:
(...)
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.

The second (optional) parameter is a callback function that will be executed once setState is completed and the component is re-rendered:

this.setState({
    iterator: this.state.iterator+1
  }, function(){
    console.log(this.state.iterator) 
});
Comments