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

141
Vistas
Hook value does not update in recurring call

I can see my state value being updated in useEffect, however, the value is still the same in a function that is being triggered every 5 seconds. Is there any way to resolve this?

const [check, setCheck] = useState(true);

// Button to toggle Check
const buttonToToggleCheckValue = () => {
    console.log("Toggle check");
    setCheck(!check);
};

// Call this function every 5 seconds
const triggeredEveryFiveSeconds = () => {
    console.log("Check value: " + check); 
};

useEffect(() => {
    console.log("useEffect Check value: " + check);
}, [check]);
---output---

Check value: true
Check value: true
Check value: true
Toggle check
useEffect Check value: false
Check value: true             <--- Value should be false
Check value: true
Check value: true
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The problem is that whenever the state changes your component gets re-rendered and initialises the state as true. You can use useRef as shown in the below snippet.

const check = useRef(true);

  // Button to toggle Check
  const buttonToToggleCheckValue = () => {
    console.log('Toggle check');
    check.current = !check.current
  };

  // Call this function every 5 seconds
  const triggeredEveryFiveSeconds = () => {
    console.log('Check value: ' + check.current);
  };

  useEffect(() => {
    console.log('useEffect Check value: ' + check.current);
  }, [check]);

  useEffect(() => {
    setInterval(() => {
      triggeredEveryFiveSeconds();
    }, 5 * 1000);
  }, []);

ref will maintain the value over multiple renders.

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