Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun May 07 2023

A simple count down timer component in React

I saw a question on Stackoverflow the other day, and I didn't have anything better to do today, so I thought I could share a solution to how to create a simple Timer component in React. So if you are building a super awesome stop watch or something, this guide might be just for you!

Final result

Image of the final result

result

Timer component

Let's dive right into it. We will create a component called Timer and let it accept a prop called minutes. Our component will only handle full minutes, so not like 8.5 etc.

Below is the full code of our component. I will go through the important parts afterwards.

import { useEffect, useState } from "react"; interface ITimerProps { minutes: number; } let secondInterval: NodeJS.Timer, minuteInterval: NodeJS.Timer; export const Timer = (props: ITimerProps) => { const [minutes, setMinutes] = useState( props.minutes < 1 ? 0 : props.minutes - 1 ); const [seconds, setSeconds] = useState(59); useEffect(() => { secondInterval = setInterval(() => { setSeconds((prev) => (prev - 1 < 0 ? 59 : prev - 1)); }, 1000); minuteInterval = setInterval(() => { setMinutes((prev) => prev - 1); }, 60000); return () => { clearInterval(secondInterval); clearInterval(minuteInterval); }; }, []); if (minutes <= 0 && seconds === 0) { clearInterval(secondInterval); clearInterval(minuteInterval); } return ( <div> {minutes <= 0 && seconds === 0 ? ( <h1>0:00</h1> ) : ( <h1> {" "} {minutes}:{seconds < 10 ? `0${seconds}` : seconds} </h1> )} </div> ); };

Some notes of the code that are worth mentioning

  • We are initialzing our minutes state variable with - 1 since we start at 59 seconds. So 2 minutes will start with 1:59 since it will take 1 second before the interval starts.

  • On mounting, we will create two intervals, one that runs every second, and one for every minute which will decrease the values accordingly.

  • When the component unmounts, we will clear our intervals to avoid memory leaks.

  • If the timer hits 0 minutes and 0 seconds, we will also clear the interval and display a static 0:00 text.

Consume it

And then we will simply just call it like this

import { Timer } from "components/timer/Timer"; <Timer minutes={10} />;

Outro

That's it. Now we have created our count down timer in React, using states and setInterval. How did you solve it? Email us here for all kinds of feedback and ideas.

All the best,

signatureSun May 07 2023
See all our articles