Rooks
HooksAnimation & Timing

useIntervalWhen

Runs the latest callback on an interval while a condition is true.

About

useIntervalWhen manages a browser interval whose lifetime follows a boolean condition. The interval keeps its schedule when only the callback changes and invokes the latest callback.

Examples

import { useState } from "react";
import { useIntervalWhen } from "rooks";

export default function IntervalCounter() {
  const [running, setRunning] = useState(false);
  const [count, setCount] = useState(0);
  useIntervalWhen(() => setCount((value) => value + 1), 1000, running, true);

  return (
    <section>
      <p role="timer">Ticks: {count}</p>
      <button type="button" onClick={() => setRunning((value) => !value)}>
        {running ? "Pause" : "Start"}
      </button>
    </section>
  );
}

Parameters

ArgumentTypeDefaultMeaning
callback() => voidrequiredLatest function invoked on each tick.
intervalDurationMsnumber0Browser interval duration in milliseconds.
whenbooleantrueCreates the interval while true.
startImmediatebooleanfalseInvokes once when an active interval is created.

Return value

The hook returns void.

Behavior and lifecycle

Changing when, duration, or startImmediate clears the current interval and, when enabled, creates a new one. An immediate call occurs on each such activation before the first timed tick. Callback identity changes do not reset the schedule. Cleanup clears the interval on disable and unmount. Exceptions thrown by the callback are not caught.

Compatibility and accessibility

The interval is created in an effect, so server rendering schedules nothing. It requires window when the effect runs. Browsers may clamp or pause background timers. Avoid overly frequent visual or live-region updates, and provide a pause control for moving or auto-updating content when applicable.

On this page