import { useEffect, useRef, useState } from 'react'; export const useCountdown = (shouldStart: boolean, duration: number = 30, delay: number = 1000) => { const [timerRunning, setTimerRunning] = useState(false); const [secondsLeft, setSecondsLeft] = useState(duration); const intervalRef = useRef(null); useEffect(() => { if (shouldStart) { setSecondsLeft(duration); setTimerRunning(true); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [shouldStart]); const stop = () => { if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } } const restart = () => { stop(); setSecondsLeft(duration); setTimerRunning(true); } useEffect(() => { if (timerRunning && intervalRef.current === null) { intervalRef.current = setInterval(() => { setSecondsLeft((prev) => { if (prev <= 1) { setTimerRunning(false); clearInterval(intervalRef.current!); intervalRef.current = null; return 0; } return prev - 1; }); }, delay); } return () => { stop(); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [timerRunning]); return { timerRunning, secondsLeft, setTimerRunning, setSecondsLeft, stop, restart }; };