useInterval
Declarative interval tied to component lifetime.
Declarative interval tied to component lifetime.
Import
import { useInterval } from '@kamod-ch/hooks'Live demo
Basic demo
Declarative interval tied to component lifetime.
Ticks: 0
import { useState } from 'preact/hooks'
import { useInterval } from '@kamod-ch/hooks'
export default function UseIntervalDemo() {
const [running, setRunning] = useState(false)
const [ticks, setTicks] = useState(0)
useInterval(() => setTicks((value) => value + 1), running ? 1000 : undefined)
return (
<div>
<p><strong>Ticks:</strong> {ticks}</p>
<div class="demo-actions">
<button type="button" onClick={() => setRunning((value) => !value)}>{running ? 'Stop' : 'Start'}</button>
<button type="button" onClick={() => setTicks(0)}>Reset</button>
</div>
</div>
)
}
API
TypeScript signature
declare const useInterval: (fn: () => void, delay?: number, options?: {
immediate?: boolean;
}) => () => void;
export default useInterval;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.