Skip to main content

useInterval

A React hook for creating declarative intervals with automatic cleanup. Under the hood, it uses the setInterval API.

React 19.2.0
npm install @plenty-hooks/use-interval

Showcase

import { useState } from 'react';
import useInterval from '@plenty-hooks/use-interval';

function Counter() {
const [count, setCount] = useState(0);
const [delay, setDelay] = useState<number | null>(1000);

useInterval(() => {
setCount((c) => c + 1);
}, delay);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setDelay(1000)}>Start</button>
<button onClick={() => setDelay(null)}>Stop</button>
</div>
);
}

API

useInterval(callback, delay)

Creates an interval that calls the provided callback function at the specified delay. The interval automatically cleans up when the component unmounts or when the delay changes.

Parameters

  • callback: () => void - The function to be called at each interval.
  • delay: number | null | undefined - The delay in milliseconds between each callback invocation. Pass null or undefined to pause/disable the interval.

Returns

  • void - This hook does not return any value.