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

127
Vistas
Different behaviour of setInterval in react vs vanilla javascript

I have been experimenting with setInterval. Both the codes were executed in Chrome. Below is my react component

function App() {
  let [value, setValue] = useState(0);

  useEffect(() => {
    const id = setInterval(() => console.log(value), 1000);

    return () => clearInterval(id);
  }, []);

  return (
    <div className="App">
      <p>{value}</p>

      <button onClick={() => setValue(value + 1)}>+</button>
      <button onClick={() => setValue(value - 1)}>-</button>
    </div>
  );
}

The console.log in setTimeout inside useEffect keeps printing 0 no matter how many times you increment or decrement the value via button click.

Following code is being executed in browser (Chrome) console

let value = 0;

setInterval(() => console.log(value), 1000);

value = 3; // can be considered as setValue (sort of)

Now the browser console prints 3 which is expected.

I wonder why there is a difference in behaviour and would appreciate if someone could point out the reason for this. Any other code snippet or link that demonstrate this even better would be great.

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

0

You need to pass value as a dependency to your useEffect. Unless you give the list of items that your effect dependent upon in the dependency array, it will keep using the initial value.

  useEffect(() => {
    const id = setInterval(() => console.log(value), 1000);

    return () => clearInterval(id);
  }, [value]);
about 4 years ago · Juan Pablo Isaza Denunciar

0

İn your example useEffect only work once when page loaded. This is why you only get console.log(0). If you want to make it when value change you need specify that in useEffect

For example

UseEffect(() =>{ console.log(value) }, [value])

In your example when you click to button, first value sets after that useEffect works and setInternals function triggered after 1s.

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