Skip to content

Instantly share code, notes, and snippets.

@JT501
Last active July 18, 2023 04:25
Show Gist options
  • Save JT501/856a5950964502cf54e7be06adb9b2f0 to your computer and use it in GitHub Desktop.
Save JT501/856a5950964502cf54e7be06adb9b2f0 to your computer and use it in GitHub Desktop.
React useCountDown Hook
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];
};
@JT501
Copy link
Author

JT501 commented Nov 3, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment