useRafInterval
Interval scheduled through requestAnimationFrame.
Interval scheduled through requestAnimationFrame.
Import
import { useRafInterval } from '@kamod-ch/hooks'Live demo
Basic demo
Interval scheduled through requestAnimationFrame.
Frame ticks: 0
import { useState } from 'preact/hooks'
import { useRafInterval } from '@kamod-ch/hooks'
export default function UseRafIntervalDemo() {
const [running, setRunning] = useState(false)
const [ticks, setTicks] = useState(0)
useRafInterval(() => setTicks((value) => value + 1), running ? 300 : undefined)
return (
<div>
<p><strong>Frame 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 function useRafInterval(fn: () => void, delay: number | undefined, options?: {
immediate?: boolean;
}): () => void;
export default useRafInterval;
/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.