Effects
useInterval
Runs a callback on a fixed interval; pause by passing null.
Demo
live · imported from hookli
0
- delay
- 1000 ms
- status
- running
import { useState } from "react";
import { useInterval } from "hookli";
export function Demo() {
const [count, setCount] = useState(0);
const [running, setRunning] = useState(true);
useInterval(() => setCount((prev) => prev + 1), running ? 1000 : null);
return (
<div>
<p>{count}</p>
<button onClick={() => setRunning((prev) => !prev)}>
{running ? "Pause" : "Resume"}
</button>
</div>
);
}Usage
import { useState } from "react";
import { useInterval } from "hookli";
export function Demo() {
const [count, setCount] = useState(0);
const [running, setRunning] = useState(true);
useInterval(() => setCount((prev) => prev + 1), running ? 1000 : null);
return (
<div>
<p>{count}</p>
<button onClick={() => setRunning((prev) => !prev)}>
{running ? "Pause" : "Resume"}
</button>
</div>
);
}API
useInterval(callback: () => void, delay: number | null): voidParameters
| Name | Type | Default | Description |
|---|---|---|---|
| callback | () => void | — | Runs on every tick. Always fires the latest callback — the hook keeps a ref, so you never re-arm the timer just to close over fresh state. |
| delay | number | null | — | Milliseconds between ticks. Pass null to pause — the interval is cleared, so nothing runs until you set a number again. |
Returns
This hook returns nothing.
Hook
The implementation, straight from hookli. Copy it, or install the package.
import { useEffect, useRef } from "react";
export const useInterval = (callback: () => void, delay: number | null) => {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay === null) return;
const id = setInterval(() => savedCallback.current(), delay);
return () => clearInterval(id);
}, [delay]);
};