Open History to see the last commit
1---
2id: useQueuer
3title: useQueuer
4---
5
6```ts
7function useQueuer<TValue, TSelected>(
8 fn,
9 options?,
10selector?): ReactQueuer<TValue, TSelected>;
11```
12
13Defined in: [queuer/useQueuer.ts:194](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/queuer/useQueuer.ts#L194)
14
15A React hook that creates and manages a Queuer instance.
16
17This is a lower-level hook that provides direct access to the Queuer's functionality without
18any built-in state management. This allows you to integrate it with any state management solution
19you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.
20
21For a hook with built-in state management, see useQueuedState.
22
23The Queuer extends the base Queue to add processing capabilities. Items are processed
24synchronously in order, with optional delays between processing each item. The queuer includes
25an internal tick mechanism that can be started and stopped, making it useful as a scheduler.
26When started, it will process one item per tick, with an optional wait time between ticks.
27
28By default uses FIFO (First In First Out) behavior, but can be configured for LIFO
29(Last In First Out) by specifying 'front' position when adding items.
30
31## State Management and Selector
32
33The hook uses TanStack Store for reactive state management. You can subscribe to state changes
34in two ways:
35
36**1. Using `queuer.Subscribe` HOC (Recommended for component tree subscriptions)**
37
38Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
39needing to pass a selector to the hook. This is ideal when you want to subscribe to state
40in child components.
41
42**2. Using the `selector` parameter (For hook-level subscriptions)**
43
44The `selector` parameter allows you to specify which state changes will trigger a re-render
45at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
46state changes occur.
47
48**By default, there will be no reactive state subscriptions** and you must opt-in to state
49tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
50re-renders and gives you full control over when your component updates.
51
52Available state properties:
53- `executionCount`: Number of items that have been processed by the queuer
54- `expirationCount`: Number of items that have been removed due to expiration
55- `isEmpty`: Whether the queuer has no items to process
56- `isFull`: Whether the queuer has reached its maximum capacity
57- `isIdle`: Whether the queuer is not currently processing any items
58- `isRunning`: Whether the queuer is active and will process items automatically
59- `items`: Array of items currently waiting to be processed
60- `itemTimestamps`: Timestamps when items were added for expiration tracking
61- `pendingTick`: Whether the queuer has a pending timeout for processing the next item
62- `rejectionCount`: Number of items that have been rejected from being added
63- `size`: Number of items currently in the queue
64- `status`: Current processing status ('idle' | 'running' | 'stopped')
65
66## Unmount behavior
67
68By default, the hook stops the queuer when the component unmounts.
69Use the `onUnmount` option to customize this. For example, to flush pending items instead:
70
71```tsx
72const queue = useQueuer(fn, {
73 started: true,
74 wait: 1000,
75 onUnmount: (q) => q.flush()
76});
77```
78
79## Type Parameters
80
81### TValue
82
83`TValue`
84
85### TSelected
86
87`TSelected` = \{
88\}
89
90## Parameters
91
92### fn
93
94(`item`) => `void`
95
96### options?
97
98[`ReactQueuerOptions`](../interfaces/ReactQueuerOptions.md)\<`TValue`, `TSelected`\> = `{}`
99
100### selector?
101
102(`state`) => `TSelected`
103
104## Returns
105
106[`ReactQueuer`](../interfaces/ReactQueuer.md)\<`TValue`, `TSelected`\>
107
108## Example
109
110```tsx
111// Default behavior - no reactive state subscriptions
112const queue = useQueuer(
113 (item) => console.log('Processing:', item),
114 { started: true, wait: 1000 }
115);
116
117// Subscribe to state changes deep in component tree using Subscribe HOC
118<queue.Subscribe selector={(state) => ({ size: state.size, isRunning: state.isRunning })}>
119 {({ size, isRunning }) => (
120 <div>Queue: {size} items, {isRunning ? 'Processing' : 'Idle'}</div>
121 )}
122</queue.Subscribe>
123
124// Opt-in to re-render when queue size changes at hook level (optimized for displaying queue length)
125const queue = useQueuer(
126 (item) => console.log('Processing:', item),
127 { started: true, wait: 1000 },
128 (state) => ({
129 size: state.size,
130 isEmpty: state.isEmpty,
131 isFull: state.isFull
132 })
133);
134
135// Opt-in to re-render when processing state changes (optimized for loading indicators)
136const queue = useQueuer(
137 (item) => console.log('Processing:', item),
138 { started: true, wait: 1000 },
139 (state) => ({
140 isRunning: state.isRunning,
141 isIdle: state.isIdle,
142 status: state.status,
143 pendingTick: state.pendingTick
144 })
145);
146
147// Opt-in to re-render when execution metrics change (optimized for stats display)
148const queue = useQueuer(
149 (item) => console.log('Processing:', item),
150 { started: true, wait: 1000 },
151 (state) => ({
152 executionCount: state.executionCount,
153 expirationCount: state.expirationCount,
154 rejectionCount: state.rejectionCount
155 })
156);
157
158// Example with custom state management and scheduling
159const [items, setItems] = useState([]);
160
161const queue = useQueuer(
162 (item) => console.log('Processing:', item),
163 {
164 started: true, // Start processing immediately
165 wait: 1000, // Process one item every second
166 onItemsChange: (queue) => setItems(queue.peekAllItems()),
167 getPriority: (item) => item.priority // Process higher priority items first
168 }
169);
170
171// Add items to process - they'll be handled automatically
172queue.addItem('task1');
173queue.addItem('task2');
174
175// Control the scheduler
176queue.stop(); // Pause processing
177queue.start(); // Resume processing
178
179// Access the selected state (will be empty object {} unless selector provided)
180const { size, isRunning, executionCount } = queue.state;
181```