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

Bartosz Salwiczek
4 min readJun 20, 2022

--

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.

--

--

Bartosz Salwiczek

I write about Software Engineering. JS/TS/Node/Vue/React/Flutter. Get access to all my articles by joining Medium https://medium.com/@bsalwiczek/membership