useInterval.ts
1 import { useEffect, useRef } from 'react' 2 3 /** 4 * A custom hook that runs a callback at a specified interval. 5 * The interval is cleared when the component unmounts. 6 * The interval is also cleared and restarted if the delay changes. 7 */ 8 export function useInterval(callback: () => void, delay: number): void { 9 const savedCallback = useRef(callback) 10 11 // Remember the latest callback 12 useEffect(() => { 13 savedCallback.current = callback 14 }, [callback]) 15 16 // Set up the interval 17 useEffect(() => { 18 function tick() { 19 savedCallback.current() 20 } 21 22 const id = setInterval(tick, delay) 23 return () => clearInterval(id) 24 }, [delay]) 25 }