Building timer in React? It’s not as simple as you may think!
How setInterval
/setTimeout specifics and component re-render time can make a difference
There are some applications that every developer builds when starting out. Hello world, ToDo apps, counters, timers… just to name a few of them.
Recently when building a new application I needed to implement a countdown timer. Easy peasy. As for everything in the Javascript world, there is a package for that — use-countdown-timer
.
But I thought: “Hey, it’s so simple thing that I’d spare this one dependency and build it on my own”.
It turned out that it was not so easy to make an accurate timer.
Naive timer
I started with a naive approach. When thinking about running something after a period of time there are two functions that come to mind — setTimeout()
and setInterval()
. setInterval()
sounds like a good choice for repetitive actions such as decreasing a number representing left time. I used it in useEffect()
hook so it’s only executed once.