Last active
June 11, 2024 00:51
-
-
Save sprobejames/30c70fc1c80d8a0d8605f7e9f11fd013 to your computer and use it in GitHub Desktop.
Reusable Countdown Hook for React
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useEffect, useState, useRef } from 'react'; | |
| const useCountdown = (targetDate) => { | |
| const countDownDate = new Date(targetDate).getTime(); | |
| const [countDown, setCountDown] = useState( | |
| countDownDate - new Date().getTime() | |
| ); | |
| const timerRef = useRef(null); | |
| const S = 60; // Seconds in a Minute | |
| const M = 60; // Minutes in an Hour | |
| const H = 24; // Hours in a Day | |
| const getReturnValues = (countDown) => { | |
| // calculate time left | |
| const days = Math.floor(countDown / (1000 * S * M * H)); | |
| const hours = Math.floor((countDown % (1000 * S * M * H)) / (1000 * S * M)); | |
| const minutes = Math.floor((countDown % (1000 * S * M)) / (1000 * M)); | |
| const seconds = Math.floor((countDown % (1000 * S)) / 1000); | |
| // prevent negative countdown, stop at 0 | |
| if (days <= 0 && hours <= 0 && minutes <= 0 && seconds <= 0) { | |
| clearInterval(timerRef.current); | |
| return [0, 0, 0, 0]; | |
| } | |
| return [days, hours, minutes, seconds]; | |
| }; | |
| useEffect(() => { | |
| timerRef.current = setInterval(() => { | |
| setCountDown(countDownDate - new Date().getTime()); | |
| }, 1000); | |
| return () => clearInterval(timerRef.current); | |
| }, [countDownDate]); | |
| return getReturnValues(countDown); | |
| }; | |
| export default useCountdown; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment