Value of count in state isn't incrementing

Viewed 41

in my app,

class App extends Component {
  constructor(props){
    super(props)
    this.state={
      count:0
    }
  }
  render() {
    return (
      <div className='App-header'>
        <button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>
      </div>
    )
  }
}

i added an event on this button :

<button onClick={()=>{this.setState({count:this.state.count=this.state.count++})}}>You Clicked This : {this.state.count} Times.</button>

but when im clicking it, value of count isn't incrementing

ps : im new to react

2 Answers

This has more to do with plain old javascript than react and state management.

Below is a small reproduction of your issue:

let y = 2;
y = y++;
console.log(y);
y = ++y;
console.log(y);

This is because of how ++ [(increment operator)](If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing.) works.

From the docs:

If used postfix, with operator after operand (for example, x++), the increment operator increments and returns the value before incrementing. If used prefix, with operator before operand (for example, ++x), the increment operator increments and returns the value after incrementing.

Also it is note worthy that you should not do anything like:

this.state.variable = randomValue;

The fix

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

will work because

this.state.count=++this.state.count

return the increment count. But state is actually updated by this.setState and you can also do:

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

When new state value is dependent on previous value

In addition to above answers, when updating state, that depends on previous state, you should use callback function in state update which receives previous state and return value is updated state

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