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

96
Views
Updating a variable during asynchronous function time out
const [value, setValue] = useState(0);
const counter = () => {
  setTimeout(() => {
    // setValue(value + 1);
    setValue((prevState) => prevState + 1);
  }, 2000);
};

counter is called when a button is pressed i.e.

<button onClick={counter}>counter</button>

Why does setValue(value + 1) update the value once if I press the button multiple times, but setValue((prevState) => prevState + 1) return the correct value relative to the amount pressed?

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

0

State updates are not always immediate. Using the previous value ensures that you are working with the current value at the point in time where the value is being set. Kent Dodds explains this well in this post. Bigger question might be, why are you wrapping this in a setTimeout?

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!