Function: useTimeout()
useTimeout(
callback,delay,options?):UseTimeoutControls
Defined in: use-timeout.ts:78
Declarative setTimeout. Calls callback once, delay milliseconds after
mount, and returns start, cancel and isPending controls.
The latest callback is always used, so changing it (for example because
it closes over state) never resets the timer. Changing delay, or
switching it between null and a number, restarts the timer; while delay
is null there is no timer, which is how you pause. The timer is cleared
on unmount.
Use start to restart the countdown, for example on every user action
(an inactivity timer) or to show something again after it was dismissed.
With autoStart: false nothing runs until you call start, and a running
timer is left alone when delay changes; the new delay applies the next
time start is called. The return value of callback is ignored. For a
recurring timer, see useInterval; for delaying a value or a burst of
calls, see useDebouncedValue and useDebouncedCallback.
Parameters
callback
() => void
The function to call when the timer elapses.
delay
number | null
The delay in milliseconds, or null for no timer.
options?
Optional behavior flags.
Returns
Stable controls to start, cancel
and check isPending on the timer.
Examples
// Auto-dismiss a notice after 3 seconds
useTimeout(onDismiss, 3000);
// Pause while hovered by switching the delay to null
const [hovered, setHovered] = useState(false);
useTimeout(onDismiss, hovered ? null : 3000);
// Start on demand, restarting the countdown on every click
const [saved, setSaved] = useState(false);
const { start } = useTimeout(() => setSaved(false), 2000, {
autoStart: false,
});
const save = () => {
setSaved(true);
start();
};
For a live, editable example, see the useTimeout docs page.