import {useState, useCallback, useRef, useEffect} from 'react';
export default function useCountdown({
countStart,
countStop = 0,
intervalMs = 1000,
isIncrement = false,
}) {
const [initialCount] = useState(countStart);
const [count, setCount] = useState(initialCount);
const intervalRef = useRef(null);
const stop = useCallback(() => {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}, []);
const start = useCallback(() => {
if (intervalRef.current !== null) return;
intervalRef.current = setInterval(() => {
setCount((prev) => {
const next = isIncrement ? prev + 1 : prev - 1;
const reachStop = isIncrement ? next >= countStop : next <= countStop;
if (reachStop) {
stop();
return countStop;
}
return next;
});
}, intervalMs);
}, [countStop, intervalMs, isIncrement, stop]);
const reset = useCallback(() => {
stop();
setCount(initialCount);
}, [initialCount, stop]);
useEffect(() => {
return stop;
}, [stop]);
return {
count,
start,
stop,
reset
};
}