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

135
Views
how to use updated state in react

This question also relates to using updated Redux state inside functions in React components. I will like to know how can I use/update state inside some form of loop in React. Example:

useEffect(() => {
    const interval = setInterval(() => {
        setCount(count + 1)
        console.log('Count:', count)
    }, 3000);
    return () => clearInterval(interval)
}, [])

This returns to console:

Count: 0
Count: 0
Count: 0
Count: 0
...

What do I need to do to avoid this? (I would like to get Count: 0, Count: 1, Count: 2 as results)

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

0

you should pass a function to setCount :

useEffect(() => {
  const interval = setInterval(() => {
    setCount(prevCount => {
      console.log('Count:', prevCount)
      return prevCount + 1;
    });
  }, 3000);
  return () => clearInterval(interval)
}, [])
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!