Open History to see the last commit
1---
2id: useAsyncQueuedState
3title: useAsyncQueuedState
4---
5
6```ts
7function useAsyncQueuedState<TValue, TSelected>(
8 fn,
9 options?,
10 selector?): [TValue[], ReactAsyncQueuer<TValue, TSelected>];
11```
12
13Defined in: [async-queuer/useAsyncQueuedState.ts:151](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-queuer/useAsyncQueuedState.ts#L151)
14
15A higher-level React hook that creates an `AsyncQueuer` instance with built-in state management.
16
17This hook combines an AsyncQueuer with React state to automatically track the queue items.
18It returns a tuple containing:
19- The current array of queued items as React state
20- The queuer instance with methods to control the queue
21
22The queue can be configured with:
23- Maximum concurrent operations
24- Maximum queue size
25- Processing function for queue items
26- Various lifecycle callbacks
27
28The state will automatically update whenever items are:
29- Added to the queue
30- Removed from the queue
31- Started processing
32- Completed processing
33
34## State Management and Selector
35
36The hook uses TanStack Store for reactive state management via the underlying async queuer instance.
37The `selector` parameter allows you to specify which async queuer state changes will trigger a re-render,
38optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
39
40**By default, there will be no reactive state subscriptions** and you must opt-in to state
41tracking by providing a selector function. This prevents unnecessary re-renders and gives you
42full control over when your component updates. Only when you provide a selector will the
43component re-render when the selected state values change.
44
45Available async queuer state properties:
46- `activeItems`: Items currently being processed by the queuer
47- `errorCount`: Number of task executions that have resulted in errors
48- `expirationCount`: Number of items that have been removed due to expiration
49- `isEmpty`: Whether the queuer has no items to process
50- `isFull`: Whether the queuer has reached its maximum capacity
51- `isIdle`: Whether the queuer is not currently processing any items
52- `isRunning`: Whether the queuer is active and will process items automatically
53- `items`: Array of items currently waiting to be processed
54- `itemTimestamps`: Timestamps when items were added for expiration tracking
55- `lastResult`: The result from the most recent task execution
56- `pendingTick`: Whether the queuer has a pending timeout for processing the next item
57- `rejectionCount`: Number of items that have been rejected from being added
58- `settleCount`: Number of task executions that have completed (success or error)
59- `size`: Number of items currently in the queue
60- `status`: Current processing status ('idle' | 'running' | 'stopped')
61- `successCount`: Number of task executions that have completed successfully
62
63## Type Parameters
64
65### TValue
66
67`TValue`
68
69### TSelected
70
71`TSelected` *extends* `Pick`\<`AsyncQueuerState`\<`TValue`\>, `"items"`\> = `Pick`\<`AsyncQueuerState`\<`TValue`\>, `"items"`\>
72
73## Parameters
74
75### fn
76
77(`value`) => `Promise`\<`any`\>
78
79### options?
80
81[`ReactAsyncQueuerOptions`](../interfaces/ReactAsyncQueuerOptions.md)\<`TValue`, `TSelected`\> = `{}`
82
83### selector?
84
85(`state`) => `TSelected`
86
87## Returns
88
89\[`TValue`[], [`ReactAsyncQueuer`](../interfaces/ReactAsyncQueuer.md)\<`TValue`, `TSelected`\>\]
90
91## Example
92
93```tsx
94// Default behavior - no reactive state subscriptions
95const [queueItems, asyncQueuer] = useAsyncQueuedState(
96 async (item) => {
97 const result = await processItem(item);
98 return result;
99 },
100 {
101 concurrency: 2,
102 maxSize: 100,
103 started: true
104 }
105);
106
107// Opt-in to re-render when queue contents change (optimized for displaying queue items)
108const [queueItems, asyncQueuer] = useAsyncQueuedState(
109 async (item) => {
110 const result = await processItem(item);
111 return result;
112 },
113 { concurrency: 2, maxSize: 100, started: true },
114 (state) => ({
115 items: state.items,
116 size: state.size,
117 isEmpty: state.isEmpty,
118 isFull: state.isFull
119 })
120);
121
122// Opt-in to re-render when processing state changes (optimized for loading indicators)
123const [queueItems, asyncQueuer] = useAsyncQueuedState(
124 async (item) => {
125 const result = await processItem(item);
126 return result;
127 },
128 { concurrency: 2, maxSize: 100, started: true },
129 (state) => ({
130 isRunning: state.isRunning,
131 isIdle: state.isIdle,
132 status: state.status,
133 activeItems: state.activeItems,
134 pendingTick: state.pendingTick
135 })
136);
137
138// Opt-in to re-render when execution metrics change (optimized for stats display)
139const [queueItems, asyncQueuer] = useAsyncQueuedState(
140 async (item) => {
141 const result = await processItem(item);
142 return result;
143 },
144 { concurrency: 2, maxSize: 100, started: true },
145 (state) => ({
146 successCount: state.successCount,
147 errorCount: state.errorCount,
148 settleCount: state.settleCount,
149 expirationCount: state.expirationCount,
150 rejectionCount: state.rejectionCount
151 })
152);
153
154// Opt-in to re-render when results are available (optimized for data display)
155const [queueItems, asyncQueuer] = useAsyncQueuedState(
156 async (item) => {
157 const result = await processItem(item);
158 return result;
159 },
160 { concurrency: 2, maxSize: 100, started: true },
161 (state) => ({
162 lastResult: state.lastResult,
163 successCount: state.successCount
164 })
165);
166
167// Add items to queue - state updates automatically
168asyncQueuer.addItem(async () => {
169 const result = await fetchData();
170 return result;
171});
172
173// Start processing
174asyncQueuer.start();
175
176// Stop processing
177asyncQueuer.stop();
178
179// queueItems reflects current queue state
180const pendingCount = asyncQueuer.peekPendingItems().length;
181
182// Access the selected async queuer state (will be empty object {} unless selector provided)
183const { size, isRunning, activeItems } = asyncQueuer.state;
184```