How to use the increment operator in React

Why when I am doing this.setState({count:this.state.count*2}) it is working, but when I am doing: this.setState({count:this.state.count++}) it is not working?

Why, and how to fix it?

Full code:

var Hello = React.createClass({
    getInitialState:function(){
    return {count:parseInt(this.props.count)}
  },
    a:function(){
    this.setState({count:this.state.count++})
    console.log(this.state)
  },
  render: function() {
    console.log(this.state)
    return <div onClick={this.a}>Click to increment the counter<b> {this.state.count} </b></div>;
  }
});

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

But this code is working:

a:function(){
    this.setState({count:this.state.count*2})
    console.log(this.state)
  },

JSFiddle: https://jsfiddle.net/69z2wepo/55100/


setState is an async function. React may batch a bunch of setStates together. So the value of this.state.count is the value at the time you make the request.

A better solutions to call a function that gets evaluated at the time the setState gets executed.

this.setState((prevState, props) => ({
    counter: prevState.counter + 1
})); 

from https://facebook.github.io/react/docs/state-and-lifecycle.html


By doing this.state.count++, you mutate the state, because it's the same thing than doing this.state.count += 1. You should never mutate the state (see https://facebook.github.io/react/docs/component-api.html). Prefer to do that instead:

this.setState({ count: this.state.count + 1 })

The setState function returns before this.state.count is incremented because you are using a post-fix operator (++). Also, setState is asynchronous, it accepts a callback as the second argument which get triggered when the state has been updated, so you should put your console.log inside of the cb.


You are trying to mutate state (access this.state.field and increase its value) that's what ++ is. It tries to increase that state value, and then assign it to new state :) Only ever mutate state by calling setState. Try

this.setState({count: this.state.count+1})

or

this.setState({(state)=>({count: state.count + 1})}

// new state variable inside function's scope, we can play with that, ++ even safely. but don't call ++ on this.state ever. In general, don't use ++, it's bad practice.
For simple assignments

a+=1 || a-=1 || a*=1 || a%=1  

are better, or even write them explicitly.

 a = a + 1