Thian Kian Phin
Thian Kian Phin

Reputation: 931

The increment ++ operator doesn't work for setting react state

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

Upvotes: 2

Views: 3541

Answers (2)

bakkal
bakkal

Reputation: 55448

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 ++

Upvotes: 6

Richard Casetta
Richard Casetta

Reputation: 446

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 !

Upvotes: 0

Related Questions