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 so that you don't have to manually clear 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.
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 so that you don't have to manually clear 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.
The useTimeout
hook can be implemented with useEffect
to create a timeout with setTimeout
for delay
milliseconds. The timeout is cleared when the component is unmounted or when the delay
is null
.
The callback
is stored using useRef
so that the pending timer can reference the latest callback.
import { useRef, useEffect } from 'react';export default function useTimeout(callback: () => void, delay: number | null) {const latestCallback = useRef(callback);latestCallback.current = callback;useEffect(() => {if (delay === null) {return;}const timeoutId = setTimeout(() => {latestCallback.current();}, delay);return () => {clearTimeout(timeoutId);};}, [delay]);}
console.log()
statements will appear here.