How to create a countdown timer hook for your React project

Ben Hur
2 min readAug 18, 2022

--

Hi there, timers are quite easy to use in JS, we have native libraries for that, but showing time being update in React/React Native components are not so simple and sometimes it gets tricky. In this post I would like to show you how to create a hook where we set a target time and it give us a full countdown for that time, including seconds, minutes, hours and days.

The main idea is to subtract the current date from the target and divide it by days, hours, minutes and seconds. After that we need to active an useEffect with a setInterval which will run every second updating our state, this is the heart of our hook, if we don't use a state here the DOM will not re-render where we want and the timer will not count.

Coding the hook

We will divide our task in three functions:

  • formatNumber: different than strings, numbers will show with a pure format, in our case instead of having 20:9 we want something like 20:09 to be displayed
  • getTimeDiff: this function will get the time diff as param, and return a formatted type for us.
  • useTimer: the hook it self, we will have the state with the time left in milliseconds and we will update it every second it pass.

To format the number is simple as this function:

Now things can get a little more complicated, to make it more simple I am using some consts here to represent time values, after that we will calculate every value we need for our return type (which we can see in the gist bellow).

Everything we did to format the return type could be done with a library like date-fns or moment JS in less steps.

And now the hook where we will set an interval and update the remaining time every 1 second.

I am not checking the current timeLeft on it, it will depend on the type of counter you want.

Conclusion

Basically in a big project this custom hook can be used in several features, the good part is that it works on React or React Native and can be customized to the type of data you need.

My consideration about that is, be pragmatic in how you want to use, remember that every time we update our state inside the hook all the parent component where we are using it will get re-rendered, once a second it is fine, but probably if we down that interval to 1ms we could start having trouble. That is all for now, and, if you want to check all the files, they are available at my GitHub.

--

--

Ben Hur
Ben Hur

Written by Ben Hur

I am a React Native Developer with passion to build things.