Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

353
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda