import { useEffect, useRef } from 'react'; /** * Hook for declarative setInterval * * Provides a React-friendly way to use intervals that automatically * cleans up on unmount and updates with callback changes. * * @param callback - Function to call on each interval * @param delay - Delay in milliseconds (null to pause) * * @example * ```typescript * function Timer() { * const [count, setCount] = useState(0); * const [isRunning, setIsRunning] = useState(true); * * useInterval( * () => { * setCount(count + 1); * }, * isRunning ? 1000 : null * ); * * return ( *
*

Count: {count}

* *
* ); * } * ``` */ export function useInterval(callback: () => void, delay: number | null): void { const savedCallback = useRef<() => void>(); // Remember the latest callback useEffect(() => { savedCallback.current = callback; }, [callback]); // Set up the interval useEffect(() => { if (delay === null) { return; } const tick = () => { if (savedCallback.current) { savedCallback.current(); } }; const id = setInterval(tick, delay); return () => { clearInterval(id); }; }, [delay]); }