Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
Value of count in state isn't incrementing

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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}))
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!