Skip to content
Source
Sign inSign up
TanStack/pacer
Open History to see the last commit

useAsyncThrottler.md

208 lines7.1 KB

1---
2id: useAsyncThrottler
3title: useAsyncThrottler
4---
5​
6```ts
7function useAsyncThrottler<TFn, TSelected>(
8 fn,
9 options,
10selector?): ReactAsyncThrottler<TFn, TSelected>;
11```
12​
13Defined in: [async-throttler/useAsyncThrottler.ts:225](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-throttler/useAsyncThrottler.ts#L225)
14​
15A low-level React hook that creates an `AsyncThrottler` instance to limit how often an async function can execute.
16​
17This hook is designed to be flexible and state-management agnostic - it simply returns a throttler instance that
18you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
19​
20Async throttling ensures an async function executes at most once within a specified time window,
21regardless of how many times it is called. This is useful for rate-limiting expensive API calls,
22database operations, or other async tasks.
23​
24Unlike the non-async Throttler, this async version supports returning values from the throttled 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 throttled function.
27​
28Error Handling:
29- If an `onError` handler is provided, it will be called with the error and throttler instance
30- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
31- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
32- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
33- The error state can be checked using the underlying AsyncThrottler instance
34​
35## State Management and Selector
36​
37The hook uses TanStack Store for reactive state management. You can subscribe to state changes
38in two ways:
39​
40**1. Using `throttler.Subscribe` HOC (Recommended for component tree subscriptions)**
41​
42Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
43needing to pass a selector to the hook. This is ideal when you want to subscribe to state
44in child components.
45​
46**2. Using the `selector` parameter (For hook-level subscriptions)**
47​
48The `selector` parameter allows you to specify which state changes will trigger a re-render
49at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
50state changes occur.
51​
52**By default, there will be no reactive state subscriptions** and you must opt-in to state
53tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
54re-renders and gives you full control over when your component updates.
55​
56Available state properties:
57- `errorCount`: Number of function executions that have resulted in errors
58- `isExecuting`: Whether the throttled function is currently executing asynchronously
59- `isPending`: Whether the throttler is waiting for the timeout to trigger execution
60- `lastArgs`: The arguments from the most recent call to maybeExecute
61- `lastExecutionTime`: Timestamp of the last function execution in milliseconds
62- `lastResult`: The result from the most recent successful function execution
63- `nextExecutionTime`: Timestamp when the next execution can occur in milliseconds
64- `settleCount`: Number of function executions that have completed (success or error)
65- `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
66- `successCount`: Number of function executions that have completed successfully
67​
68## Unmount behavior
69​
70By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.
71Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
72Use the `onUnmount` option to customize this. For example, to flush pending work instead:
73​
74```tsx
75const throttler = useAsyncThrottler(fn, {
76 wait: 1000,
77 onUnmount: (t) => t.flush()
78});
79```
80​
81Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
82If your throttled function updates React state, those updates may run after the component has
83unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
84accordingly when using onUnmount with flush.
85​
86## Type Parameters
87​
88### TFn
89​
90`TFn` *extends* `AnyAsyncFunction`
91​
92### TSelected
93​
94`TSelected` = \{
95\}
96​
97## Parameters
98​
99### fn
100​
101`TFn`
102​
103### options
104​
105[`ReactAsyncThrottlerOptions`](../interfaces/ReactAsyncThrottlerOptions.md)\<`TFn`, `TSelected`\>
106​
107### selector?
108​
109(`state`) => `TSelected`
110​
111## Returns
112​
113[`ReactAsyncThrottler`](../interfaces/ReactAsyncThrottler.md)\<`TFn`, `TSelected`\>
114​
115## Example
116​
117```tsx
118// Default behavior - no reactive state subscriptions
119const asyncThrottler = useAsyncThrottler(
120 async (id: string) => {
121 const data = await api.fetchData(id);
122 return data; // Return value is preserved
123 },
124 { wait: 1000 }
125);
126​
127// Subscribe to state changes deep in component tree using Subscribe HOC
128<asyncThrottler.Subscribe selector={(state) => ({ isExecuting: state.isExecuting, isPending: state.isPending })}>
129 {({ isExecuting, isPending }) => (
130 <div>{isExecuting || isPending ? 'Loading...' : 'Ready'}</div>
131 )}
132</asyncThrottler.Subscribe>
133​
134// Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
135const asyncThrottler = useAsyncThrottler(
136 async (id: string) => {
137 const data = await api.fetchData(id);
138 return data;
139 },
140 { wait: 1000 },
141 (state) => ({
142 isExecuting: state.isExecuting,
143 isPending: state.isPending,
144 status: state.status
145 })
146);
147​
148// Opt-in to re-render when results are available (optimized for data display)
149const asyncThrottler = useAsyncThrottler(
150 async (id: string) => {
151 const data = await api.fetchData(id);
152 return data;
153 },
154 { wait: 1000 },
155 (state) => ({
156 lastResult: state.lastResult,
157 successCount: state.successCount,
158 settleCount: state.settleCount
159 })
160);
161​
162// Opt-in to re-render when error state changes (optimized for error handling)
163const asyncThrottler = useAsyncThrottler(
164 async (id: string) => {
165 const data = await api.fetchData(id);
166 return data;
167 },
168 {
169 wait: 1000,
170 onError: (error) => console.error('API call failed:', error)
171 },
172 (state) => ({
173 errorCount: state.errorCount,
174 status: state.status
175 })
176);
177​
178// Opt-in to re-render when timing information changes (optimized for timing displays)
179const asyncThrottler = useAsyncThrottler(
180 async (id: string) => {
181 const data = await api.fetchData(id);
182 return data;
183 },
184 { wait: 1000 },
185 (state) => ({
186 lastExecutionTime: state.lastExecutionTime,
187 nextExecutionTime: state.nextExecutionTime
188 })
189);
190​
191// With state management and return value
192const [data, setData] = useState(null);
193const { maybeExecute, state } = useAsyncThrottler(
194 async (query) => {
195 const result = await searchAPI(query);
196 setData(result);
197 return result; // Return value can be used by the caller
198 },
199 {
200 wait: 2000,
201 leading: true, // Execute immediately on first call
202 trailing: false // Skip trailing edge updates
203 }
204);
205​
206// Access the selected state (will be empty object {} unless selector provided)
207const { isExecuting, lastResult } = state;
208```