Function: useInterval()
useInterval(
callback,delay,options?):void
Defined in: use-interval.ts:43
Declarative setInterval. Calls callback every delay milliseconds while
delay is a number, and pauses while it is null.
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 interval. The interval is cleared
on unmount.
With immediate, the callback also runs once whenever the interval starts:
on mount, when resuming from null, and when delay changes. Under React
StrictMode in development this means an extra call, like any effect.
Parameters
callback
() => void
The function to call on every tick.
delay
number | null
The interval in milliseconds, or null to pause.
options?
Optional behavior flags.
Returns
void
Examples
const [count, setCount] = useState(0);
useInterval(() => setCount((c) => c + 1), 1000);
// Pause and resume by toggling the delay
const [running, setRunning] = useState(true);
useInterval(poll, running ? 5000 : null, { immediate: true });
For a live, editable example, see the useInterval docs page.