Skip to main content

Function: useRateLimitedCallback()

useRateLimitedCallback<A>(callback, options): RateLimitedFunction<A>

Defined in: use-rate-limited-callback.ts:125

Returns a stable function that runs callback at most limit times per windowMs, using a token bucket.

The bucket starts full, so up to limit calls run immediately as a burst. Each call spends a token, and tokens refill smoothly at limit / windowMs per millisecond, up to limit. This sets it apart from useDebouncedCallback (waits for a quiet period) and useThrottledValue (one update per interval): bursts are allowed, but the average rate is not.

When no token is left, the call is dropped (default) or, with overflow: "queue", queued and run in order as tokens refill, up to maxQueue. The returned function reports whether a call ran or was queued (true) or dropped (false), and onLimited receives the dropped arguments. Use remaining and pending to read the limiter's state, and cancel to empty the queue. They read the current state and do not re-render your component.

The returned function keeps the same identity for the lifetime of the component and always runs the latest callback and options, so it is safe in dependency arrays and long-lived listeners. A new limit or windowMs applies from the next call or refill, without resetting spent tokens. The return value of callback is ignored. On unmount the queue and timer are cleared and later calls are ignored (they return false), so nothing runs after unmount.

Type Parameters​

A​

A extends unknown[]

The argument list of the callback.

Parameters​

callback​

(...args) => void

The function to limit.

options​

UseRateLimitedCallbackOptions<A>

The limit, window and overflow behavior.

Returns​

RateLimitedFunction<A>

A rate-limited function with cancel, remaining and pending.

Examples​

// At most 5 searches every 10 seconds, extra ones are dropped
const search = useRateLimitedCallback(
(query: string) => fetchResults(query),
{
limit: 5,
windowMs: 10_000,
onLimited: () => toast("Slow down a little"),
}
);

return <input onChange={(e) => search(e.target.value)} />;
// Send events in order, at most 2 per second, holding up to 50 back
const track = useRateLimitedCallback(sendEvent, {
limit: 2,
windowMs: 1000,
overflow: "queue",
maxQueue: 50,
});

For a live, editable example, see the useRateLimitedCallback docs page.