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

201
Visualizações
When cleanup function of UseEffect triggering clearInterval() function?

I am making a timer in a Tenzie game. When a user clicks a button, onClick function sets the isTimerActive state to true which was initially false and tenzie state is also false to default and when user complete the game tenzie state sets to true.

     React.useEffect(() => {
      let timer = null;

       if(isTimerActive && !tenzie){
        timer = setInterval(() => {
           setTime(prevSecond => prevSecond + 1);
        }, 1000);
      }
     
       return () => {
        clearInterval(timer);
       }
  }, [tenzie, isTimerActive])

I want to know when React runs this cleanup function and if it runs it every time it runs useEffect then why my timer is working ?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here the simple answer is cleanup function of useEffect runs only when the component gets unmount, it never runs each the useEffect's callback gets executed, it only runs if your component is getting un-mount.

Reff docs: https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect

Its good to have cleanup function for these scenario (as you are using setInterval) because you don't want setInterval to call even after you component gets unmount. So its better to clear the interval in the clean up function before un mounting the component.

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