useInterval

Utility

A React hook that provides a declarative way to set up intervals that are automatically cleaned up when the component unmounts, with support for dynamic delays and pausing.

Demo

1. Simple Counter

A simple counter that increments every second. You can pause and resume the interval.
0

2. Stopwatch Timer

A stopwatch timer with start, stop, and reset functionality.
0.0s

3. Progress Bar

A progress bar that automatically fills up and stops at 100%.
0%

Installation

npm install @thibault.sh/hooks

Usage

import { useInterval } from "@thibault.sh/hooks";

function Counter() {
  const [count, setCount] = useState(0);
  const [isRunning, setIsRunning] = useState(true);

  useInterval(
    () => {
      setCount(count + 1);
    },
    isRunning ? 1000 : null
  );

  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={() => setIsRunning(!isRunning)}>
        {isRunning ? "Pause" : "Resume"}
      </button>
    </div>
  );
}

API Reference

Parameters

callback

The function to call on each interval. This function should contain any state updates or side effects you want to run periodically.

Type: () => void

delay

The time in milliseconds between each callback invocation. Pass null to pause the interval. The delay can be changed dynamically to adjust the interval timing.

Type: number | null

Features

Automatic Cleanup

Intervals are automatically cleared when the component unmounts or when the delay changes, preventing memory leaks and unexpected behavior.

Dynamic Control

Easily pause and resume intervals by passing null as the delay, or dynamically adjust the interval timing by changing the delay value.

Declarative API

Provides a clean, declarative way to handle intervals in React components, making code more maintainable and easier to understand.

Type Safety

Full TypeScript support ensures type safety for callback functions and delay values, catching potential errors at compile time.

Common Use Cases

Polling

Periodically fetch data from an API to keep the UI in sync with the server. The interval can be paused when the component is not visible.

Animations

Create smooth animations or transitions by updating values at a fixed interval. Perfect for progress bars, countdowns, or simple game loops.

Auto-save

Automatically save form data or document changes at regular intervals, with the ability to pause when no changes are detected.