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

156
Vistas
Correct way to clear interval in component did mount in React

Im trying to clear an interval when the component is unmounted in a class based component in react. I have done some research on this and saw that in the componentWillUnmount lifecycle function, people are storing the actual function in a variable instead of just straight away clearing the interval. For example:

      componentDidMount() {
        const { stock } = this.props;
// Fetch data once user lands on page
        this.fetchData(stock);
// Fetch data every hour
        setInterval(() => {
          this.fetchData(stock);
          console.log('setInterval ran');
        }, 3600000);
      }
   
    
      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
        const refreshFetch = clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }
    
      async fetchData(stock) {
        const data = await getAvgPriceHistory(stock);
        if (data && data[stock].length) {
          const dataArray = data[stock].map((arr) => {
            return arr[1];
          }).reverse();
          this.setState({
            data: dataArray,
            isLoaded: true
          });
        } else {
          // straight line if not found.
          this.setState({
            data: [1, 1],
            isLoaded: true
          });
        }
        console.log('Data fetched!');
      }

Meanwhile, the way I am used to doing this in the componentWillUnmount function without defining a variable like so:

      componentWillUnmount() {
        const { stock } = this.props;
// Remove interval
       clearInterval(this.fetchData(stock));
        console.log('setInterval cleared');
      }

Is there any benefits to doing one or the other?

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

0

setInterval return an id. You can use it with clearInterval to destroy it.

https://developer.mozilla.org/en-US/docs/Web/API/setInterval

let intervalId;

...

intervalId = setInterval(fn, time);

...

clearInterval(intervalId);
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