Skip to main content

useInterval

A declarative setInterval. It calls your callback every delay milliseconds, pauses when delay is null, and always runs the latest callback without resetting the timer.

When to use it​

  • Counters, clocks and countdowns.
  • Polling an endpoint, with the ability to pause (for example when a tab is hidden, combined with useDocVisible).
  • Any recurring work that reads fresh props or state without stale closures.

Demo​

Pause the counter and drag the delay slider, then enable polling and open the Console tab to see the immediate option in action.

Loading demo…

Signature​

interface UseIntervalOptions {
immediate?: boolean;
}

function useInterval(
callback: () => void,
delay: number | null,
options?: UseIntervalOptions
): void;
ParameterTypeDescription
callback() => voidCalled on every tick. The latest version is always used.
delaynumber | nullInterval in milliseconds. null pauses the interval.
options.immediatebooleanAlso call once when the interval starts. Defaults to false.

Returns: nothing.

Usage notes​

  • Changing callback never resets the timer, so it is safe to close over state or props.
  • Changing delay, or switching it between null and a number, restarts the interval. Resuming waits a full delay before the first tick.
  • With immediate, the callback also runs whenever the interval starts: on mount, when resuming from null, and when delay changes. Under React StrictMode in development, effects run twice, so expect an extra call.
  • The interval is cleared on unmount.
  • Browsers throttle timers in background tabs, so ticks are not exact. Use timestamps (for example Date.now()) when you need accurate elapsed time.
  • Only need to run something once after a delay? Use useTimeout.
  • Need a pause/resume toggle? Keep a boolean in state and pass running ? delay : null.

Example​

const [count, setCount] = useState(0);
const [running, setRunning] = useState(true);

useInterval(() => setCount((c) => c + 1), running ? 1000 : null);

Hook source​

View useInterval source

use-interval.ts
import { useEffect } from "react";

import { useLatest } from "./use-latest";

/** Options for {@link useInterval}. */
export interface UseIntervalOptions {
/** Also invoke the callback once as soon as the interval starts. Default is `false`. */
immediate?: boolean;
}

/**
* 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.
*
* @param callback - The function to call on every tick.
* @param delay - The interval in milliseconds, or `null` to pause.
* @param options - Optional {@link UseIntervalOptions | behavior} flags.
*
* @example
* ```tsx
* const [count, setCount] = useState(0);
* useInterval(() => setCount((c) => c + 1), 1000);
* ```
*
* @example
* ```tsx
* // 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](https://altalyst-solutions.github.io/hookify/hooks/use-interval).
*/
export const useInterval = (
callback: () => void,
delay: number | null,
options?: UseIntervalOptions
): void => {
const callbackRef = useLatest(callback);
const immediateRef = useLatest(options?.immediate ?? false);

useEffect(() => {
if (delay === null) return;

if (immediateRef.current) callbackRef.current();
const id = setInterval(() => callbackRef.current(), delay);
return () => clearInterval(id);
}, [delay, callbackRef, immediateRef]);
};