2

I tried to do a simple counter with react, and I found that ++ doesn't work. I wonder why.

This worked

..

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

But this will not work

..

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

You can try it here https://jsfiddle.net/Lwvbe2o2

2 Answers 2

5

Why

Because x++ expression first returns the value of x then it increments it, while ++x first increments it, then returns that incremented value.

Just for experimentation purposes, you can verify this by using the preincrement like this

// Don't do this, it's just to explain why it works.
addCount () {
  this.setState({count: ++this.state.count})
}

Then it'll do what you want, however it's not idiotmatic, because it does mutate directly this.state.count.

Idiomatic way

In ReactJS you don't want to mutate this.state.count directly, so your first example is more idiomatic:

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

References

MDN postfix/prefix increment operator ++

2
  • Note that I am answering to "I wonder why" in your question. Otherwise this.setState({count:this.state.count + 1}) is more idiomatic.
    – bakkal
    Oct 4, 2016 at 7:24
  • ah make sense! tq Oct 4, 2016 at 8:19
0

When you do ´a = b++´, you first assign the value of b to a, then you increment b. It's called post incrementation. In your example it's the same : ´count´ will be equal to ´this.state.count´ (So the value will be the same) and then you increment ´this.state.count´, but it will be replace by ´count´ when setState finish because you change the state. setState is here to set your variable, don't mutate it in this method.

Your first proposition is the way to do what you want.

Hope this helps !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.