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

351
Vistas
Why do you need to use clearInterval to reset the timer in React?

In the following code:

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  

Why do you need to return a cleanup function that resets the interval object? In my understanding, since the interval function object was not created with useCallback(), the function should be re-initialized with each render and therefore have no memory of past interval values. Why is a cleanup function needed to clear it before the next render?

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

0

Why is a cleanup function needed to clear it before the next render?

(emphasis mine)

It's not and it's not what this code does.

By passing an empty dependency list to useEffect ([]) you are effectively telling React to only run this hook the first time the component renders, not(!) every time the component re-renders.

Now, clearing the interval when the component gets unmounted/destroyed (which is what this code does) is necessary, otherwise the interval would keep running (and throw an error eventually since you cannot update the state of an unmounted component).

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