Last active
July 18, 2023 04:25
-
-
Save JT501/856a5950964502cf54e7be06adb9b2f0 to your computer and use it in GitHub Desktop.
React useCountDown Hook
This file contains 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, useRef, useState } from 'react'; | |
export const useCountDown: ( | |
total: number, | |
ms?: number, | |
) => [number, () => void, () => void, () => void] = ( | |
total: number, | |
ms: number = 1000, | |
) => { | |
const [counter, setCountDown] = useState(total); | |
const [startCountDown, setStartCountDown] = useState(false); | |
// Store the created interval | |
const intervalId = useRef<number>(); | |
const start: () => void = () => setStartCountDown(true); | |
const pause: () => void = () => setStartCountDown(false); | |
const reset: () => void = () => { | |
clearInterval(intervalId.current); | |
setStartCountDown(false); | |
setCountDown(total); | |
}; | |
useEffect(() => { | |
intervalId.current = setInterval(() => { | |
startCountDown && counter > 0 && setCountDown(counter => counter - 1); | |
}, ms); | |
// Clear interval when count to zero | |
if (counter === 0) clearInterval(intervalId.current); | |
// Clear interval when unmount | |
return () => clearInterval(intervalId.current); | |
}, [startCountDown, counter, ms]); | |
return [counter, start, pause, reset]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Demo: https://codesandbox.io/s/usecountdown-hook-56lqv