Function: useInterval()
@arolariu/components / useInterval
Function: useInterval()
useInterval(
callback,delay):void
Defined in: hooks/useInterval.tsx:58
Executes a callback function at specified intervals with automatic cleanup.
Parameters
callback
() => void
The function to execute at each interval.
delay
number
The interval delay in milliseconds, or null to pause the interval.
Returns
void
Remarks
This hook provides a declarative interface for setInterval that automatically
handles cleanup on unmount and ensures the latest callback is always invoked
(preventing stale closures). Setting the delay to null pauses the interval,
which is useful for implementing play/pause functionality.
Unlike raw setInterval, this hook guarantees that the interval is cleared
when the component unmounts or when the delay changes, preventing memory leaks
and unexpected behavior.
Examples
function Timer() {
const [count, setCount] = useState(0);
useInterval(() => {
setCount((c) => c + 1);
}, 1000);
return <div>Count: {count}</div>;
}
function PausableTimer() {
const [count, setCount] = useState(0);
const [isRunning, setIsRunning] = useState(true);
useInterval(
() => {
setCount((c) => c + 1);
},
isRunning ? 1000 : null,
);
return (
<div>
<div>Count: {count}</div>
<button onClick={() => setIsRunning(!isRunning)}>
{isRunning ? "Pause" : "Resume"}
</button>
</div>
);
}