Skip to Content
ohooks

useRafCallback

Throttles a callback so it executes at most once per requestAnimationFrame with the latest arguments.

Loading preview...

The useRafCallback hook wraps a function so repeated calls within the same frame coalesce into a single requestAnimationFrame callback invoked with the most recent arguments, and automatically cancels any pending frame on unmount.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useRafCallback.json

Usage

Examples

High-Frequency Pointer Tracking

Throttle onPointerMove updates to the display refresh rate so DOM updates stay synchronized with browser repaints.

Cancelling a Pending Frame

Call .cancel() to abort a scheduled animation frame or .isPending() to check whether a frame is currently queued.

API Reference

RafScheduledFunction

Frame-throttled function returned by the hook, including .cancel() and .isPending() methods.

Property
Specification
cancelrequired
function
Cancels any pending animation frame invocation.
flushrequired
function
Immediately executes a pending invocation and cancels the scheduled frame.
isPendingrequired
function
Returns true if an animation frame invocation is currently scheduled.