Skip to content

useInterval

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useInterval

A declarative setInterval hook that safely handles cleanup and React's closure staleness issues. It guarantees that the callback always has access to the most recent state and props without needing to reset the interval timer.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation, which starts the interval immediately on mount.

import { useState } from 'react';
import { useInterval } from 'react-hook-lab';

function BasicClock() {
  const [seconds, setSeconds] = useState(0);

  // Automatically starts on mount, and cleans up on unmount
  useInterval(() => {
    setSeconds(s => s + 1);
  }, 1000);

  return <div>Seconds elapsed: {seconds}</div>;
}

Common (Standard Usage)

Manually pausing and resuming a background polling process.

import { useState } from 'react';
import { useInterval } from 'react-hook-lab';

function DataPoller() {
  const [data, setData] = useState([]);
  
  const { stop, start, isRunning } = useInterval(() => {
    fetch('/api/live-data').then(res => res.json()).then(setData);
  }, 5000);

  return (
    <div>
      <p>Poller is {isRunning() ? 'Active' : 'Paused'}</p>
      <button onClick={start}>Resume Polling</button>
      <button onClick={stop}>Pause Polling</button>
      <ul>{data.map((d: any) => <li key={d.id}>{d.value}</li>)}</ul>
    </div>
  );
}

Advanced (All Parameters)

An exhaustive example demonstrating resetting the timer and dynamically checking the status.

import { useState } from 'react';
import { useInterval } from 'react-hook-lab';

function AdvancedStopwatch() {
  const [ticks, setTicks] = useState(0);

  const { start, stop, restart, isRunning } = useInterval(() => {
    setTicks(t => t + 1);
  }, 100); // 100ms interval

  return (
    <div>
      <h2>Stopwatch: {(ticks / 10).toFixed(1)}s</h2>
      <button onClick={start} disabled={isRunning()}>Start</button>
      <button onClick={stop} disabled={!isRunning()}>Stop</button>
      <button onClick={() => { stop(); setTicks(0); }}>Reset</button>
      <button onClick={restart}>Restart from current time</button>
    </div>
  );
}

API Reference

Parameters

  • callback (Required)
    • Type: () => void
    • Description: The function to execute on each interval tick. This callback is internally wrapped in a ref, ensuring it never captures stale state and never requires inclusion in dependency arrays.
  • delay (Required)
    • Type: number
    • Description: The interval delay in milliseconds.

Return Object

Returns UseIntervalReturn:

  • start (() => void): Function to manually start the interval.
  • stop (() => void): Function to manually cancel the running interval.
  • restart (() => void): Clears and restarts the interval timer back from 0.
  • isRunning (() => boolean): Returns true if the interval is currently active and ticking.

Clone this wiki locally