Timers

Use setInterval, setTimeout and requestAnimationFrame from a component without writing the cleanup, and build a watchdog with useTimeout’s restart.

On this page

An interval

viewer.tsx
useInterval(5000, () => {
  post({ type: 'alive' });
});

useInterval(ms, callback) calls the latest callback every ms milliseconds while mounted. The example tells another window this one is alive, every five seconds.

null stops it, and a different ms starts the count again.

A timeout

hint.tsx
const [showHint, setShowHint] = useState(false);

useTimeout(3000, () => {
  setShowHint(true);
});

useTimeout(ms, callback) calls the callback once, ms after mounting. The example shows a hint after three seconds.

It is not called if the component unmounts first, and null cancels it.

restart

presenter.tsx
const restart = useTimeout(15_000, () => {
  window.close();
});

useBroadcastChannel(channelName, {
  parse: parseAlive,
  onMessage: restart,
Each message starts the wait again
});

useTimeout returns restart, which starts the wait again from now. Calling it re-renders the component.

The example is a watchdog that closes the presenter’s window. Each sign of life from the viewer’s window starts the wait again, and fifteen seconds without one closes it.

Every frame

search-results.tsx
const [count, setCount] = useState(20);

useAnimationFrame(count < items.length, () => {
Stops once every row is drawn
  startTransition(() => {
    setCount(count + 50);
  });
});

return items
  .slice(0, count)
  .map((item) => <Row item={item} key={item.id} />);

useAnimationFrame(running, callback) calls callback before every frame the browser paints, with the frame’s timestamp. While running is false it calls nothing; pass true to call it for as long as the component is mounted.

The example draws a long list fifty rows a frame, so no single task draws it all.

callback is the last committed render’s. Frames that come before the transition commits read the same count, so they add one batch, not one per frame.

Refused values

A negative, infinite or NaN ms throws an error starting with useInterval: ms must be a non-negative number of milliseconds or null.

useTimeout refuses the same values, with useTimeout: at the start of the error.

k8ordo

React libraries that use Baseline features without holding back.