63 lines
1.3 KiB
TypeScript
63 lines
1.3 KiB
TypeScript
|
|
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 (
|
||
|
|
* <div>
|
||
|
|
* <p>Count: {count}</p>
|
||
|
|
* <button onClick={() => setIsRunning(!isRunning)}>
|
||
|
|
* {isRunning ? 'Pause' : 'Resume'}
|
||
|
|
* </button>
|
||
|
|
* </div>
|
||
|
|
* );
|
||
|
|
* }
|
||
|
|
* ```
|
||
|
|
*/
|
||
|
|
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]);
|
||
|
|
}
|