Counter value in state can't be incremented, but adding +1 works

Challenge: Render Conditionally from Props

Link to the challenge:

I was following hte freeCodeCamp React Tutorial and when completing the challenge " React: Render Conditionally from Props" I wonder why I can manipulate the counter value in the state by adding + 1 but not by incrementing it ++.

The code which I’m refering to:

handleClick() {
  this.setState(state => ({
    counter: state.counter + 1 // works fine
    //counter: state.counter++   // doesn't work

Is this because ++ would mutate the state directly? Or am I missing something?

Actually it returns the value before increment if used postfix^^
From MDN

The increment operator increments (adds one to) its operand and returns a value.
If used postfix, with operator after operand (for example, x++), then it increments and returns the value before incrementing.
If used prefix, with operator before operand (for example, ++x), then it increments and returns the value after incrementing.

Happy coding! :smiley:

1 Like