HooksuseInterval

useInterval()

The useInterval() hook makes using setInterval inside React components declarative and safe. It solves the common "stale closure" problem where the interval callback cannot access the latest state props.

Import

typescript
import { useInterval } from 'the-react-hooks';

Usage

Counter
0
Update Interval Speed
Component.tsx
import { useInterval } from 'the-react-hooks';
import { useState } from 'react';

export const Component = () => {
  const [count, setCount] = useState(0);
  const [delay, setDelay] = useState(1000);
  const [isPlaying, setIsPlaying] = useState(true);

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

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={() => setIsPlaying(!isPlaying)}>
        {isPlaying ? 'Pause' : 'Resume'}
      </button>
    </div>
  );
}

API

Arguments

  • callback () => void The function to be executed every interval.
  • delay number | null The time in milliseconds between function calls. Pass null to pause/stop the interval.

Returns

This hook returns void.