Sometimes, we want to create a countdown timer with React.
In this article, we’ll look at how to create a countdown timer with React.
Create a Countdown Timer with React
We can create a countdown timer by creating a timer component that updates the remaining time regularly.
To do this, we write:
import React, { useEffect, useState } from "react";
const Timer = (props) => {
const { initialMinute = 0, initialSeconds = 0 } = props;
const [minutes, setMinutes] = useState(initialMinute);
const [seconds, setSeconds] = useState(initialSeconds);
useEffect(() => {
const myInterval = setInterval(() => {
if (seconds > 0) {
setSeconds(seconds - 1);
}
if (seconds === 0) {
if (minutes === 0) {
clearInterval(myInterval);
} else {
setMinutes(minutes - 1);
setSeconds(59);
}
}
}, 1000);
return () => {
clearInterval(myInterval);
};
});
return (
<div>
{minutes === 0 && seconds === 0 ? null : (
<h1>
{minutes}:{seconds < 10 ? `0${seconds}` : seconds}
</h1>
)}
</div>
);
};
export default function App() {
return (
<>
<Timer initialMinute={5} initialSeconds={0} />
</>
);
}
We create the Timer
component that takes the initialMinute
and initialSeconds
props that sets the initial time.
Then we use the useState
prop to create the minutes
and seconds
state.
Next, we call the useEffect
hook with a callback that creates a timer with setInterval
.
The timer runs every second.
The setInterval
callback checks if the seconds is bigger than 0 and calls setSeconds
to decrease the seconds.
If seconds
is 0 and minutes
is 0, then we call clearInteraval
to stop the timer.
Otherwise, we call setMinutes
to minutes — 1
and call setSeconds
to 59 decrements the minute.
Then we return a callback that calls clearInterval
to clear the timer.
Below that, we render the minutes
and seconds
onto the screen.
If seconds
is less than 10 then we add a 0 in front of it.
Conclusion
We can create a countdown timer by creating a timer component that updates the remaining time regularly.