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

402
Views
How do I specify the type of setInterval function in typeScript using React useState() hook?

I have created a timer app using react and typeScript.
In the Project I need to store the instance of setInterval() in useState() hook which I'll use to clear the setInterval() instance.
My timer instance look like this.

const [timer, setTimer] = useState<NodeJS.Timer>();

I'm using this function to clear the timer instance

  const stop = () => {
    clearInterval(timer);
    setTimerOn(false);
  };

But the issue with this approach is that inside the stop function clearInterval is showing an error because the type of timer is NodeJS.timer | undefined and only NodeJS.timer type is allowed in clearInterval function.

To remove the undefined type from the useState I have created an dummy setInterval instace and use it as the initial value in useState as shown in the image below.

enter image description here enter image description here

However I'm wondering whether my approach is correct or it is just a hacky solution? I want to know a proper approach for this.

about 4 years ago · Juan Pablo Isaza
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!