Skip to main content

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

ParameterTypeDefaultDescription
callback() => void-The function to run on each interval tick.
intervalnumber | null1000The time in milliseconds between executions. Pass null to pause the interval.

Return Value

useInterval returns an object with the following method:

PropertyTypeDescription
clear() => voidStops the interval when called.

Behavior

  • Runs callback every interval milliseconds.
  • Passing null as 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 clear function to stop the interval manually.
  • Clears the interval automatically on unmount.