Vishnu Paspunoor Vishnu Paspunoor - 4 months ago 13
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 () {
iterator: this.state.iterator + 1
render: function () {
return <button onClick={this.handleClick}>{this.state.iterator}</button>;

<Hello name="World"/>,

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?



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:

    iterator: this.state.iterator+1
  }, function(){