62 lines
1.4 KiB
TypeScript
Executable file
62 lines
1.4 KiB
TypeScript
Executable file
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) | undefined>(undefined);
|
|
|
|
// 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]);
|
|
}
|