Open History to see the last commit
1---
2id: useAsyncRateLimiter
3title: useAsyncRateLimiter
4---
5
6```ts
7function useAsyncRateLimiter<TFn, TSelected>(
8 fn,
9 options,
10selector?): ReactAsyncRateLimiter<TFn, TSelected>;
11```
12
13Defined in: [async-rate-limiter/useAsyncRateLimiter.ts:231](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-rate-limiter/useAsyncRateLimiter.ts#L231)
14
15A low-level React hook that creates an `AsyncRateLimiter` instance to limit how many times an async function can execute within a time window.
16
17This hook is designed to be flexible and state-management agnostic - it simply returns a rate limiter instance that
18you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
19
20Rate limiting allows an async function to execute up to a specified limit within a time window,
21then blocks subsequent calls until the window passes. This is useful for respecting API rate limits,
22managing resource constraints, or controlling bursts of async operations.
23
24Unlike the non-async RateLimiter, this async version supports returning values from the rate-limited function,
25making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
26instead of setting the result on a state variable from within the rate-limited function.
27
28The rate limiter supports two types of windows:
29- 'fixed': A strict window that resets after the window period. All executions within the window count
30 towards the limit, and the window resets completely after the period.
31- 'sliding': A rolling window that allows executions as old ones expire. This provides a more
32 consistent rate of execution over time.
33
34Error Handling:
35- If an `onError` handler is provided, it will be called with the error and rate limiter instance
36- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
37- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
38- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
39- The error state can be checked using the underlying AsyncRateLimiter instance
40- Rate limit rejections (when limit is exceeded) are handled separately from execution errors via the `onReject` handler
41
42## State Management and Selector
43
44The hook uses TanStack Store for reactive state management. You can subscribe to state changes
45in two ways:
46
47**1. Using `rateLimiter.Subscribe` HOC (Recommended for component tree subscriptions)**
48
49Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
50needing to pass a selector to the hook. This is ideal when you want to subscribe to state
51in child components.
52
53**2. Using the `selector` parameter (For hook-level subscriptions)**
54
55The `selector` parameter allows you to specify which state changes will trigger a re-render
56at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
57state changes occur.
58
59**By default, there will be no reactive state subscriptions** and you must opt-in to state
60tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
61re-renders and gives you full control over when your component updates.
62
63Available state properties:
64- `errorCount`: Number of function executions that have resulted in errors
65- `executionTimes`: Array of timestamps when executions occurred for rate limiting calculations
66- `isExecuting`: Whether the rate-limited function is currently executing asynchronously
67- `lastResult`: The result from the most recent successful function execution
68- `rejectionCount`: Number of function executions that have been rejected due to rate limiting
69- `settleCount`: Number of function executions that have completed (success or error)
70- `successCount`: Number of function executions that have completed successfully
71
72## Unmount behavior
73
74By default, the hook aborts any in-flight execution when the component unmounts.
75Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
76Use the `onUnmount` option to customize this.
77
78## Type Parameters
79
80### TFn
81
82`TFn` *extends* `AnyAsyncFunction`
83
84### TSelected
85
86`TSelected` = \{
87\}
88
89## Parameters
90
91### fn
92
93`TFn`
94
95### options
96
97[`ReactAsyncRateLimiterOptions`](../interfaces/ReactAsyncRateLimiterOptions.md)\<`TFn`, `TSelected`\>
98
99### selector?
100
101(`state`) => `TSelected`
102
103## Returns
104
105[`ReactAsyncRateLimiter`](../interfaces/ReactAsyncRateLimiter.md)\<`TFn`, `TSelected`\>
106
107## Example
108
109```tsx
110// Default behavior - no reactive state subscriptions
111const asyncRateLimiter = useAsyncRateLimiter(
112 async (id: string) => {
113 const data = await api.fetchData(id);
114 return data; // Return value is preserved
115 },
116 { limit: 5, window: 1000 } // 5 calls per second
117);
118
119// Subscribe to state changes deep in component tree using Subscribe HOC
120<asyncRateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount, isExecuting: state.isExecuting })}>
121 {({ rejectionCount, isExecuting }) => (
122 <div>Rejected: {rejectionCount}, {isExecuting ? 'Executing' : 'Idle'}</div>
123 )}
124</asyncRateLimiter.Subscribe>
125
126// Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
127const asyncRateLimiter = useAsyncRateLimiter(
128 async (id: string) => {
129 const data = await api.fetchData(id);
130 return data;
131 },
132 { limit: 5, window: 1000 },
133 (state) => ({ isExecuting: state.isExecuting })
134);
135
136// Opt-in to re-render when results are available (optimized for data display)
137const asyncRateLimiter = useAsyncRateLimiter(
138 async (id: string) => {
139 const data = await api.fetchData(id);
140 return data;
141 },
142 { limit: 5, window: 1000 },
143 (state) => ({
144 lastResult: state.lastResult,
145 successCount: state.successCount
146 })
147);
148
149// Opt-in to re-render when error/rejection state changes (optimized for error handling)
150const asyncRateLimiter = useAsyncRateLimiter(
151 async (id: string) => {
152 const data = await api.fetchData(id);
153 return data;
154 },
155 {
156 limit: 5,
157 window: 1000,
158 onError: (error) => console.error('API call failed:', error),
159 onReject: (rateLimiter) => console.log('Rate limit exceeded')
160 },
161 (state) => ({
162 errorCount: state.errorCount,
163 rejectionCount: state.rejectionCount
164 })
165);
166
167// Opt-in to re-render when execution metrics change (optimized for stats display)
168const asyncRateLimiter = useAsyncRateLimiter(
169 async (id: string) => {
170 const data = await api.fetchData(id);
171 return data;
172 },
173 { limit: 5, window: 1000 },
174 (state) => ({
175 successCount: state.successCount,
176 errorCount: state.errorCount,
177 settleCount: state.settleCount,
178 rejectionCount: state.rejectionCount
179 })
180);
181
182// Opt-in to re-render when execution times change (optimized for window calculations)
183const asyncRateLimiter = useAsyncRateLimiter(
184 async (id: string) => {
185 const data = await api.fetchData(id);
186 return data;
187 },
188 { limit: 5, window: 1000 },
189 (state) => ({ executionTimes: state.executionTimes })
190);
191
192// With state management and return value
193const [data, setData] = useState(null);
194const { maybeExecute, state } = useAsyncRateLimiter(
195 async (query) => {
196 const result = await searchAPI(query);
197 setData(result);
198 return result; // Return value can be used by the caller
199 },
200 {
201 limit: 10,
202 window: 60000, // 10 calls per minute
203 onReject: (rateLimiter) => {
204 console.log(`Rate limit exceeded. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`);
205 },
206 onError: (error) => {
207 console.error('API call failed:', error);
208 }
209 }
210);
211
212// Access the selected state (will be empty object {} unless selector provided)
213const { isExecuting, lastResult, rejectionCount } = state;
214```