Implement a useTimeout hook that invokes a callback function after a specified delay.
Note that the hooks can be called again with different values since the initial call:
The primary benefit of useTimeout is that you do not have to manually call clearTimeout() if the component unmounts before the timer expires.
export default function Component() {const [loading, setLoading] = useState(true);useTimeout(() => setLoading(false), 1000);return (<div><p>{loading ? 'Loading' : 'Ready'}</p></div>);}
callback: () => void: A function to be called after the specified delaydelay: number | null: The delay in milliseconds before the invocation of the callback function. If null, the timeout is clearedNothing.
useTimeout(callback, delay) schedules one future call of the latest callback and returns nothing. The hook tracks two things: whether a timeout should currently exist, and which callback that timeout should invoke when it fires.
The main correctness concern is stale closures. A pending timeout should not restart just because the callback identity changes, but it still needs to run the newest callback if that change happens before the timeout fires.
useRef stores the latest callback so the scheduled timeout can read the current function.useEffect manages the timeout lifecycle based on delay, and null disables scheduling.import { useRef, useEffect } from 'react';/*** @param {() => void} callback* @param {number | null} delay*/export default function useTimeout(callback, delay) {// Keep the timeout pointed at the latest callback without restarting it on every render.const latestCallback = useRef(callback);latestCallback.current = callback;useEffect(() => {if (delay === null) {return;}const timeoutId = setTimeout(() => {latestCallback.current();}, delay);return () => {clearTimeout(timeoutId);};}, [delay]);}
Storing the callback in a ref is what keeps the timer stable without forcing the effect to restart every time the callback function changes.
delay replaces the pending timeout, and unmounting clears it.console.log() statements will appear here.