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

useAsyncQueuer.md

219 lines7.1 KB

1---
2id: useAsyncQueuer
3title: useAsyncQueuer
4---
5​
6```ts
7function useAsyncQueuer<TValue, TSelected>(
8 fn,
9 options?,
10selector?): ReactAsyncQueuer<TValue, TSelected>;
11```
12​
13Defined in: [async-queuer/useAsyncQueuer.ts:235](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-queuer/useAsyncQueuer.ts#L235)
14​
15A lower-level React hook that creates an `AsyncQueuer` instance for managing an async queue of items.
16​
17Features:
18- Priority queue support via getPriority option
19- Configurable concurrency limit
20- Task success/error/completion callbacks
21- FIFO (First In First Out) or LIFO (Last In First Out) queue behavior
22- Pause/resume task processing
23- Task cancellation
24- Item expiration to clear stale items from the queue
25​
26Tasks are processed concurrently up to the configured concurrency limit. When a task completes,
27the next pending task is processed if below the concurrency limit.
28​
29Error Handling:
30- If an `onError` handler is provided, it will be called with the error and queuer instance
31- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
32- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
33- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
34- The error state can be checked using the underlying AsyncQueuer instance
35​
36## State Management and Selector
37​
38The hook uses TanStack Store for reactive state management. You can subscribe to state changes
39in two ways:
40​
41**1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**
42​
43Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
44needing to pass a selector to the hook. This is ideal when you want to subscribe to state
45in child components.
46​
47**2. Using the `selector` parameter (For hook-level subscriptions)**
48​
49The `selector` parameter allows you to specify which state changes will trigger a re-render
50at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
51state changes occur.
52​
53**By default, there will be no reactive state subscriptions** and you must opt-in to state
54tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
55re-renders and gives you full control over when your component updates.
56​
57Available state properties:
58- `activeItems`: Items currently being processed by the queuer
59- `errorCount`: Number of task executions that have resulted in errors
60- `expirationCount`: Number of items that have been removed due to expiration
61- `isEmpty`: Whether the queuer has no items to process
62- `isFull`: Whether the queuer has reached its maximum capacity
63- `isIdle`: Whether the queuer is not currently processing any items
64- `isRunning`: Whether the queuer is active and will process items automatically
65- `items`: Array of items currently waiting to be processed
66- `itemTimestamps`: Timestamps when items were added for expiration tracking
67- `lastResult`: The result from the most recent task execution
68- `pendingTick`: Whether the queuer has a pending timeout for processing the next item
69- `rejectionCount`: Number of items that have been rejected from being added
70- `settleCount`: Number of task executions that have completed (success or error)
71- `size`: Number of items currently in the queue
72- `status`: Current processing status ('idle' | 'running' | 'stopped')
73- `successCount`: Number of task executions that have completed successfully
74​
75## Unmount behavior
76​
77By default, the hook stops the queuer and aborts any in-flight task executions when the component unmounts.
78Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
79Use the `onUnmount` option to customize this. For example, to flush pending items instead:
80​
81```tsx
82const queuer = useAsyncQueuer(fn, {
83 concurrency: 2,
84 started: false,
85 onUnmount: (q) => q.flush()
86});
87```
88​
89Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
90If your task function updates React state, those updates may run after the component has
91unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
92accordingly when using onUnmount with flush.
93​
94## Type Parameters
95​
96### TValue
97​
98`TValue`
99​
100### TSelected
101​
102`TSelected` = \{
103\}
104​
105## Parameters
106​
107### fn
108​
109(`value`) => `Promise`\<`any`\>
110​
111### options?
112​
113[`ReactAsyncQueuerOptions`](../interfaces/ReactAsyncQueuerOptions.md)\<`TValue`, `TSelected`\> = `{}`
114​
115### selector?
116​
117(`state`) => `TSelected`
118​
119## Returns
120​
121[`ReactAsyncQueuer`](../interfaces/ReactAsyncQueuer.md)\<`TValue`, `TSelected`\>
122​
123## Example
124​
125```tsx
126// Default behavior - no reactive state subscriptions
127const asyncQueuer = useAsyncQueuer(
128 async (item) => {
129 const result = await processItem(item);
130 return result;
131 },
132 { concurrency: 2, maxSize: 100, started: false }
133);
134​
135// Subscribe to state changes deep in component tree using Subscribe HOC
136<asyncQueuer.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>
137 {({ size, isRunning }) => (
138 <div>Queue: {size} items, {isRunning ? 'Processing' : 'Idle'}</div>
139 )}
140</asyncQueuer.Subscribe>
141​
142// Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)
143const asyncQueuer = useAsyncQueuer(
144 async (item) => {
145 const result = await processItem(item);
146 return result;
147 },
148 { concurrency: 2, maxSize: 100, started: false },
149 (state) => ({
150 size: state.size,
151 isEmpty: state.isEmpty,
152 isFull: state.isFull
153 })
154);
155​
156// Opt-in to re-render when processing state changes (optimized for loading indicators)
157const asyncQueuer = useAsyncQueuer(
158 async (item) => {
159 const result = await processItem(item);
160 return result;
161 },
162 { concurrency: 2, maxSize: 100, started: false },
163 (state) => ({
164 isRunning: state.isRunning,
165 isIdle: state.isIdle,
166 status: state.status,
167 activeItems: state.activeItems,
168 pendingTick: state.pendingTick
169 })
170);
171​
172// Opt-in to re-render when execution metrics change (optimized for stats display)
173const asyncQueuer = useAsyncQueuer(
174 async (item) => {
175 const result = await processItem(item);
176 return result;
177 },
178 { concurrency: 2, maxSize: 100, started: false },
179 (state) => ({
180 successCount: state.successCount,
181 errorCount: state.errorCount,
182 settleCount: state.settleCount,
183 expirationCount: state.expirationCount,
184 rejectionCount: state.rejectionCount
185 })
186);
187​
188// Opt-in to re-render when results are available (optimized for data display)
189const asyncQueuer = useAsyncQueuer(
190 async (item) => {
191 const result = await processItem(item);
192 return result;
193 },
194 {
195 concurrency: 2,
196 maxSize: 100,
197 started: false,
198 onSuccess: (result) => {
199 console.log('Item processed:', result);
200 },
201 onError: (error) => {
202 console.error('Processing failed:', error);
203 }
204 },
205 (state) => ({
206 lastResult: state.lastResult,
207 successCount: state.successCount
208 })
209);
210​
211// Add items to queue
212asyncQueuer.addItem(newItem);
213​
214// Start processing
215asyncQueuer.start();
216​
217// Access the selected state (will be empty object {} unless selector provided)
218const { size, isRunning, activeItems } = asyncQueuer.state;
219```