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

348
Views
Nextjs: update state not work in interval

This is my state:

const [time, setTime] = useState(10)

And this is my handler:

const runTimer = () => {
    useEffect(() => {
        const interval = setInterval(() => {
            console.log(time)
            if (time > 0) {
                setTime(time - 1)
            } else {
                console.log("End")
            }
        }, 1000);
        return () => clearInterval(interval)
    }, [])
}

My log:

9
9
9
9
9
.
.
.

Why setTime doesn't work ?

time variable most increase per 1000 delay

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

0

The function you pass to useEffect has closed over the timer variable from the first time the component rendered.

Each time the component renders, the current value of the state is read and a timer variable is created with that value.

You aren't accessing that variable though. The variable you are accessing on the interval never changes, so every time you access it, it is still 10.


State functions are passed the current value as an argument, so use that instead.

const Timer = () => {
    const [timer, setTime] = useState(10);
    useEffect(() => {
        const interval = setInterval(() => {
            setTime(
                (currentTime) => {
                    if (currentTime > 0) {
                        return currentTime - 1;
                    } else {
                        console.log("End of interval");
                        clearInterval(interval);
                        return currentTime;
                    }
                }
            );
        }, 1000);
        return () => clearInterval(interval)
    }, [])
    return <p>{timer}</p>
}
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!