jsx
1import { useRef, useEffect, useState } from 'react';23const useInterval = (callback, delay) => {4 const savedCallback = useRef();56 useEffect(() => {7 savedCallback.current = callback;8 }, [callback]);910 useEffect(() => {11 const tick = () => {12 savedCallback.current();13 };1415 if (delay !== null) {16 let id = setInterval(tick, delay);17 return () => clearInterval(id);18 }19 }, [delay]);20};2122// Usage23const Timer = () => {24 const [seconds, setSeconds] = useState(0);2526 useInterval(() => {27 setSeconds(seconds + 1);28 }, 1000);2930 return <div>Seconds: {seconds}</div>;31};