useInterval
useInterval runs a callback repeatedly at a specified interval.
Usage
import { useState } from "react";
import { useInterval } from "hookify-react";
export default function UseIntervalExample() {
const [count, setCount] = useState(0);
const { clear } = useInterval(() => setCount((prev) => prev + 1), 1000);
return (
<div>
<p>Counter: {count}</p>
<button onClick={clear}>Stop Timer</button>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
callback | () => void | - | The function to run on each interval tick. |
interval | number | null | 1000 | The time in milliseconds between executions. Pass null to pause the interval. |
Return Value
useInterval returns an object with the following method:
| Property | Type | Description |
|---|---|---|
clear | () => void | Stops the interval when called. |
Behavior
- Runs
callbackeveryintervalmilliseconds. - Passing
nullas the interval pauses execution. - Always invokes the latest
callback; changing it does not restart the timer, so it does not need to be memoized. - Returns a
clearfunction to stop the interval manually. - Clears the interval automatically on unmount.