3

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

Abhimanyu Sharma
  • 858
  • 1
  • 9
  • 17

2 Answers2

3

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

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • ++this.state.count mutates state directly which is not recommended. Instead callback should be used this.setState(previousState => {count: previousState.count + 1}) – Andyally Jun 24 '22 at 13:08
  • Yes, but that was not the scope of the question. So instead of writing a long explanation I just added a link – Tushar Shahi Jun 24 '22 at 13:34
1

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}))
Andyally
  • 863
  • 1
  • 9
  • 22