snippet
useCountdown
snippet
useCountdown
Last updated December 31st, 2022
When working with Date time objects in Javascript, it's important to remember that all the times are formatted in milliseconds (ms). Therefore, we're going to write a small helper function to help us express date times in days, hours, minutes, and seconds. This helper function is important for the hook to work correctly.
Have you ever wanted to add a countdown feature to your application? This handy little hook will help you do that!
After importing this hook into your app, you pass in a target date & time. The useCountdown
hook will then return four properties and these include the days, hours, minutes, and seconds until the timer is done. You can then render these values in your app to show a countdown.
Caution
This hook uses the JavaScript date object, therefore, it's important that you format the date string correctly. Further, if a time is not included in the date string then javascript will automatically assume a time of 00:00:00.
import { useEffect, useState } from "react";
const useCountdown = (targetDate) => {
const countDownDate = new Date(targetDate).getTime();
const delta = countDownDate - new Date().getTime();
const [countDown, setCountDown] = useState(delta);
useEffect(() => {
const interval = setInterval(() => {
setCountDown(countDownDate - new Date().getTime());
}, 1000);
const time = convertValue(countDown);
const stopTimer = time.every((item) => item === "0");
if (stopTimer) {
clearInterval(interval);
}
return () => clearInterval(interval);
}, [countDownDate, countDown]);
return convertValue(countDown);
};
const convertValue = (countDown) => {
const days = String(Math.floor(countDown / (1000 * 60 * 60 * 24))).padStart(
1,
"0"
);
const hours = String(
Math.floor((countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60))
).padStart(2, "0");
const minutes = String(
Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60))
).padStart(2, "0");
const seconds = String(Math.floor((countDown % (1000 * 60)) / 1000)).padStart(
2,
"0"
);
return [days, hours, minutes, seconds];
};
import useCountdown from "./useCountdown";
const App = () => {
const targetDate = "01/01/2023 00:00:00";
const [days, hours, minutes, seconds] = useCountdown(targetDate);
return (
<>
<p><{`There are ${days} days, ${hours} hours, ${minutes} minutes, ${seconds} seconds, left until your target date & time`}</p>
</>
);
};