Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

154
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda