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

124
Views
Confusion with how setState works

I am confused with how setState works.

Here is a portion of my code:

handleBarsChange(value) {
  this.setState({numberOfbars: value});
  this.resetArray();
}

apparently, when the resetArray() function executes and tries to access the this.state.numberOfbars state variable, setState hasn't updated the value yet.

I want some explanation on how and where should the setState be executed and when can i expect to see the change.

Thank you!

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

0

setState is asynchronous. It has a second callback argument that can be used to run code after a state transition. This isn't always the best approach, but with the very narrow example provided, it's hard to say.

this.setState({numberOfBars: value}, () => { this.resetArray() })

From the react docs:

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. Generally we recommend using componentDidUpdate() for such logic instead.

https://reactjs.org/docs/react-component.html#setstate

about 4 years ago · Juan Pablo Isaza Report

0

The fact is that setState() function is async so even if you run code after you call it, some state may not be updated yet.

The solution is implement a callback when the state was updated succesfully (setState(<state>, <callback>)), for example:

handleBarsChange(value){
    this.setState({numberOfbars: value}, () => {
        this.resetArray();
    });
}
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!