function useAsyncRateLimitedCallback<TFn, TSelected>(
fn,
options,
selector): (...args) => Promise<ReturnType<TFn>>
function useAsyncRateLimitedCallback<TFn, TSelected>(
fn,
options,
selector): (...args) => Promise<ReturnType<TFn>>
Defined in: react-pacer/src/async-rate-limiter/useAsyncRateLimitedCallback.ts:61
A React hook that creates a rate-limited version of an async callback function. This hook is a convenient wrapper around the useAsyncRateLimiter hook, providing a stable, async rate-limited function reference for use in React components.
Async rate limiting is a "hard limit" approach for async functions: it allows all calls until the limit is reached, then blocks (rejects) subsequent calls until the window resets. Unlike throttling or debouncing, it does not attempt to space out or collapse calls. This can lead to bursts of rapid executions followed by periods where all calls are blocked.
The async rate limiter supports two types of windows:
For smoother execution patterns, consider:
Async rate limiting should primarily be used when you need to enforce strict limits on async operations, like API rate limits or other scenarios requiring hard caps on execution frequency.
This hook provides a simpler API compared to useAsyncRateLimiter, making it ideal for basic async rate limiting needs. However, it does not expose the underlying AsyncRateLimiter instance.
For advanced usage requiring features like:
Consider using the useAsyncRateLimiter hook instead.
• TFn extends AnyAsyncFunction
• TSelected = {}
TFn
AsyncRateLimiterOptions<TFn>
(state) => TSelected
Function
...Parameters<TFn>
Promise<ReturnType<TFn>>
// Rate limit async API calls to maximum 5 calls per minute with a sliding window
const makeApiCall = useAsyncRateLimitedCallback(
async (data: ApiData) => {
return fetch('/api/endpoint', { method: 'POST', body: JSON.stringify(data) });
},
{
limit: 5,
window: 60000, // 1 minute
windowType: 'sliding',
onReject: () => {
console.warn('API rate limit reached. Please wait before trying again.');
}
}
);
// Rate limit async API calls to maximum 5 calls per minute with a sliding window
const makeApiCall = useAsyncRateLimitedCallback(
async (data: ApiData) => {
return fetch('/api/endpoint', { method: 'POST', body: JSON.stringify(data) });
},
{
limit: 5,
window: 60000, // 1 minute
windowType: 'sliding',
onReject: () => {
console.warn('API rate limit reached. Please wait before trying again.');
}
}
);
Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.