-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseCountdown.jsx
More file actions
24 lines (23 loc) · 777 Bytes
/
useCountdown.jsx
File metadata and controls
24 lines (23 loc) · 777 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const useCountdown = (targetDate) => {
const targetTimestamp = new Date(targetDate).getTime()
const [remainingTime, setRemainingTime] = useState(() => {
return Math.max(0, targetTimestamp - Date.now());
});
useEffect(() => {
if (remainingTime <= 0) {
setRemainingTime(0)
}
const intervalId = setInterval(() => {
const newRemaining = targetTimestamp - Date.now();
if (newRemaining <= 0) {
setRemainingTime(0)
clearTimeout(intervalId)
} else {
setRemainingTime(newRemaining)
}
}, 1000)
return () => clearTimeout(intervalId)
}, [targetTimestamp]);
return remainingTime
}
export default useCountdown