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

6

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

Sign up to request clarification or add additional context in comments.

2 Comments

Note that I am answering to "I wonder why" in your question. Otherwise this.setState({count:this.state.count + 1}) is more idiomatic.
ah make sense! tq
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 !

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.