JAVASCRIPT
Implement a Dynamic Countdown Timer with `useCountdown` Hook
Build a reusable `useCountdown` hook to easily add dynamic and precise countdown timers to your React applications, perfect for promotions or events.
import React, { useState, useEffect, useRef } from 'react';
function useCountdown(targetDate) {
const countDownDate = new Date(targetDate).getTime();
const [countDown, setCountDown] = useState(
countDownDate - new Date().getTime()
);
useEffect(() => {
const interval = setInterval(() => {
setCountDown(countDownDate - new Date().getTime());
}, 1000);
return () => clearInterval(interval);
}, [countDownDate]);
return getReturnValues(countDown);
}
const getReturnValues = (countDown) => {
// calculate time left
const days = Math.floor(countDown / (1000 * 60 * 60 * 24));
const hours = Math.floor((countDown % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const minutes = Math.floor((countDown % (1000 * 60 * 60)) / (1000 * 60));
const seconds = Math.floor((countDown % (1000 * 60)) / 1000);
return [days, hours, minutes, seconds];
};
function CountdownDisplay() {
const threeDaysFromNow = new Date();
threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 3);
const [days, hours, minutes, seconds] = useCountdown(threeDaysFromNow.toISOString());
if (days + hours + minutes + seconds <= 0) {
return <p>Countdown Over!</p>;
}
return (
<div>
<p>{days}D {hours}H {minutes}M {seconds}S</p>
</div>
);
}
export default CountdownDisplay;
How it works: The `useCountdown` hook provides a dynamic, real-time countdown timer. It takes a `targetDate` and calculates the remaining time, updating every second using `setInterval`. The `useEffect` hook ensures the interval is properly set up and cleared when the component unmounts. It returns an array of days, hours, minutes, and seconds, which can be displayed in any React component to show time remaining until the target date.