Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!