Simple code that implement countdown on React.

Steve Kim
2 min readFeb 25, 2022
Photo by Lukas Blazek on Unsplash

On web or mobile application, you often encounter a countdown. The most frequent one is when the application asks a confirmation code sent to your phonenumber. It gives you a limited time for you to enter the code, starting its countdown from 60 to 0.

In this blog, I would like to share how we implemented the countdown with a simple custom hook using useState() and useEffect(). It starts from a certain user-given integer such as 60, and goes down to 0. On reaching 0, it executes an “timeoutFunction” passed in as one of the parameters.

The below is the code at my gist.

useCountdown.ts

It takes four parameters. All four are required.

  1. startFrom.

It must be an integer where countdown start from such as 60.

2. startCountDown.

It must be a boolean value whose value can be either true or false. If you want the countdown starts right after the component mounts, you pass true. Other wise if you want a user’s action triggers the countdown, you pass false. In the example of the confirmation code, it was passed false because it must start countdown after a user enters his phonenumber.

3. timeoutFunction.

It must be a function. This function is supposed to be triggered when the countdown is finished. In other words, the function is triggered when the counter reaches 0.

4. stopCountdown.

It must be a boolean. Initally, this value must be false. If this value changes from false to true in the middle of countdown, this resets the counter back to the startFrom.

This is for resetting the countdown. When you need to start over the countdown, this value must be turned from false to true.

The followings are the screenshots of my react-native project implementing this hook.

This is not that highly complex code. But I thought this may save someone’s precious time. I hope that happens.

Thank you for reading my blog.

--

--

Steve Kim

A Certified Public Accountant / Hobbyist-programmer-but-dead-serious-specializing JavaScript, ReactJS, NextJS and AWS.