useInterval
Runs a callback at specified intervals.
Installation
Props
Prop | Type | Default | Description |
---|---|---|---|
callback | () => void | () => {} | The function to execute at each interval. |
delay | number | null | null | The delay in milliseconds between each execution. |
Key Features & Details
- The hook sets up an interval using
setInterval
and cleans up withclearInterval
. - Passing
null
asdelay
pauses the interval. - Ensures the latest callback is always invoked by using a ref.
Examples
Basic Usage
import { useInterval } from '@/registry/hooks/use-interval';
function Component() {
useInterval(() => {
console.log('tick');
}, 1000);
return <div>Check the console for ticks every second.</div>;
}
Pause and Resume
import { useState } from 'react';
import { useInterval } from '@/registry/hooks/use-interval';
function Timer() {
const [count, setCount] = useState(0);
const [active, setActive] = useState(true);
useInterval(() => setCount((c) => c + 1), active ? 1000 : null);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setActive((a) => !a)}>
{active ? 'Pause' : 'Resume'}
</button>
</div>
);
}