-
Notifications
You must be signed in to change notification settings - Fork 0
useInterval
Saurav-TB-Pandey edited this page Aug 8, 2026
·
2 revisions
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.
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>;
}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>
);
}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>
);
}-
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.
- Type:
-
delay(Required)- Type:
number - Description: The interval delay in milliseconds.
- Type:
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): Returnstrueif the interval is currently active and ticking.
Built with ❤️ by Saurav-TB-Pandey. | Report an Issue | NPM