Open History to see the last commit
1---
2id: useQueuedState
3title: useQueuedState
4---
5
6```ts
7function useQueuedState<TValue, TSelected>(
8 fn,
9 options?,
10 selector?): [TValue[], (item, position?, runOnItemsChange?) => boolean, ReactQueuer<TValue, TSelected>];
11```
12
13Defined in: [queuer/useQueuedState.ts:119](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/queuer/useQueuedState.ts#L119)
14
15A React hook that creates a queuer with managed state, combining React's useState with queuing functionality.
16This hook provides both the current queue state and queue control methods.
17
18The queue state is automatically updated whenever items are added, removed, or reordered in the queue.
19All queue operations are reflected in the state array returned by the hook.
20
21The queue can be started and stopped to automatically process items at a specified interval,
22making it useful as a scheduler. When started, it will process one item per tick, with an
23optional wait time between ticks.
24
25The hook returns a tuple containing:
26- The current queue state as an array
27- The queue instance with methods for queue manipulation
28
29## State Management and Selector
30
31The hook uses TanStack Store for reactive state management via the underlying queuer instance.
32The `selector` parameter allows you to specify which queuer state changes will trigger a re-render,
33optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.
34
35**By default, there will be no reactive state subscriptions** and you must opt-in to state
36tracking by providing a selector function. This prevents unnecessary re-renders and gives you
37full control over when your component updates. Only when you provide a selector will the
38component re-render when the selected state values change.
39
40Available queuer state properties:
41- `executionCount`: Number of items that have been processed by the queuer
42- `expirationCount`: Number of items that have been removed due to expiration
43- `isEmpty`: Whether the queuer has no items to process
44- `isFull`: Whether the queuer has reached its maximum capacity
45- `isIdle`: Whether the queuer is not currently processing any items
46- `isRunning`: Whether the queuer is active and will process items automatically
47- `items`: Array of items currently waiting to be processed
48- `itemTimestamps`: Timestamps when items were added for expiration tracking
49- `pendingTick`: Whether the queuer has a pending timeout for processing the next item
50- `rejectionCount`: Number of items that have been rejected from being added
51- `size`: Number of items currently in the queue
52- `status`: Current processing status ('idle' | 'running' | 'stopped')
53
54## Type Parameters
55
56### TValue
57
58`TValue`
59
60### TSelected
61
62`TSelected` *extends* `Pick`\<`QueuerState`\<`TValue`\>, `"items"`\> = `Pick`\<`QueuerState`\<`TValue`\>, `"items"`\>
63
64## Parameters
65
66### fn
67
68(`item`) => `void`
69
70### options?
71
72[`ReactQueuerOptions`](../interfaces/ReactQueuerOptions.md)\<`TValue`, `TSelected`\> = `{}`
73
74### selector?
75
76(`state`) => `TSelected`
77
78## Returns
79
80\[`TValue`[], (`item`, `position?`, `runOnItemsChange?`) => `boolean`, [`ReactQueuer`](../interfaces/ReactQueuer.md)\<`TValue`, `TSelected`\>\]
81
82## Example
83
84```tsx
85// Default behavior - no reactive state subscriptions
86const [items, addItem, queue] = useQueuedState(
87 (item) => console.log('Processing:', item),
88 {
89 initialItems: ['item1', 'item2'],
90 started: true,
91 wait: 1000,
92 getPriority: (item) => item.priority
93 }
94);
95
96// Opt-in to re-render when queue contents change (optimized for displaying queue items)
97const [items, addItem, queue] = useQueuedState(
98 (item) => console.log('Processing:', item),
99 { started: true, wait: 1000 },
100 (state) => ({
101 items: state.items,
102 size: state.size,
103 isEmpty: state.isEmpty
104 })
105);
106
107// Opt-in to re-render when processing state changes (optimized for loading indicators)
108const [items, addItem, queue] = useQueuedState(
109 (item) => console.log('Processing:', item),
110 { started: true, wait: 1000 },
111 (state) => ({
112 isRunning: state.isRunning,
113 isIdle: state.isIdle,
114 status: state.status,
115 pendingTick: state.pendingTick
116 })
117);
118
119// Opt-in to re-render when execution metrics change (optimized for stats display)
120const [items, addItem, queue] = useQueuedState(
121 (item) => console.log('Processing:', item),
122 { started: true, wait: 1000 },
123 (state) => ({
124 executionCount: state.executionCount,
125 expirationCount: state.expirationCount,
126 rejectionCount: state.rejectionCount
127 })
128);
129
130// Add items to queue
131const handleAdd = (item) => {
132 addItem(item);
133};
134
135// Start automatic processing
136const startProcessing = () => {
137 queue.start();
138};
139
140// Stop automatic processing
141const stopProcessing = () => {
142 queue.stop();
143};
144
145// Manual processing still available
146const handleProcess = () => {
147 const nextItem = queue.getNextItem();
148 if (nextItem) {
149 processItem(nextItem);
150 }
151};
152
153// Access the selected queuer state (will be empty object {} unless selector provided)
154const { size, isRunning, executionCount } = queue.state;
155```