Skip to content

useRafTimeout

Timeout scheduled through requestAnimationFrame.

Timeout scheduled through requestAnimationFrame.

Import

import { useRafTimeout } from '@kamod-ch/hooks'

Live demo

Basic demo

Timeout scheduled through requestAnimationFrame.

Status: idle

import { useState } from 'preact/hooks'
import { useRafTimeout } from '@kamod-ch/hooks'

export default function UseRafTimeoutDemo() {
  const [armed, setArmed] = useState(false)
  const [status, setStatus] = useState('idle')
  useRafTimeout(() => { if (armed) setStatus('completed') }, armed ? 600 : undefined)

  return (
    <div>
      <p><strong>Status:</strong> {status}</p>
      <button type="button" onClick={() => { setStatus('waiting'); setArmed(true) }}>Start RAF timeout</button>
    </div>
  )
}

API

TypeScript signature
declare function useRafTimeout(fn: () => void, delay: number | undefined): () => void;
export default useRafTimeout;
/

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.