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

444
Vistas
Why a simple `useEffect` is not taking updated value when it is warping any "setInterval/timeout" inside

Why a simple useEffect is not taking updated value when it is warping any setInterval/timeout inside;

Code sandbox

where variable stopped to initial value;

import { useState, useEffect } from "react";
let timerRef;
const StopWatch = () => {
  const [time, setTime] = useState(0);
  const [isPause, setPause] = useState(false);
  useEffect(() => {
    timerRef = setInterval(() => {
      console.log({ time });
      if (!isPause) {
        setTime(time + 1);
      }
    }, 5000);
    return () => clearInterval(timerRef);
  }, []);
  const startWatch = () => {
    setPause(false);
  };
  const stopWatch = () => {
    setPause(true);
  };
  return (
    <>
      time: {time}
      <button onClick={startWatch}>Start</button>
      <button onClick={stopWatch}>stop</button>
    </>
  );
};
export { StopWatch };

output

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

pass dependency of time and this should work

useEffect(() => {
    let _time = time;
    console.log({ time });
    timerRef = setInterval(() => {
      console.log({ _time });
      if (!isPause) {
        setTime(_time + 1);
      }
    }, 5000);
    return () => clearInterval(timerRef);
  }, [time]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

That is because you are accessing time value from the closure, and since you are defining setTimeout handler only once (on initialization) then it will always refer to that initial value for time. I suggest, for this use case, just to use state updater with callback, and like that it will provide you mechanism to easily update state with previos one, and by not accessing state directly. Just rewrite setTime(_time + 1) to setTime(prevTime => prevTime + 1)

about 4 years ago · Juan Pablo Isaza Denunciar

0

CodeSandbox already warned you about that.

enter image description here

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