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

185
Views
Why is the output different with React setState()

I don't know why

  • When I use this.setState({count: count+1} Clicking multiple times will only update count once
  • When I use this.setState({count: this.setState.count}) Each click updates the count
  • Why different?
       class Demo extends React.Component {
            state = {count: 0};
            render() {
                const {count} = this.state;
                return  <button onClick={() => this.setState({count: count+1})}>count</button>
            }
            shouldComponentUpdate(){
                return false;
            } 

        }
  • Environment react@16.8.4
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Because their scopes are different.

this.setState({count: this.setState.count+1})actions of loading state.count number and reassignment are in same onClick event scope.

But count variable in this.setState({count: count+1}) is defined in upper render() scope and onClick event only receive count as upper level variable. Therefore, render() function is only run once, so count in render() only initialized once(loading state.count only once); when you click button, only onClick event scope will be executed(reassignment actions will be executed multiple times), rather than render() scope. That is why count variable in onClick event will be always 0.

There is a simple equivalent example to your case:

state={count:0}

function upperLevel() {
  
  
  let {count} = state;

  function downlevel() {
    state = {
      count: count + 1
    }
    console.log(state);
  }

  downlevel();
  downlevel();
  downlevel();


}

upperLevel()

If we move let {count} = state; into downlevel() then the number will be increased.

state = {count: 0}

function upperLevel() {
  //let {count} = state;
  function downlevel() {
    let {count} = state;
    state = {count: count + 1 }
    console.log(state);
  }

  downlevel();
  downlevel();
  downlevel();
}

upperLevel()

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!