Open History to see the last commit
1---
2id: useBatcher
3title: useBatcher
4---
5
6```ts
7function useBatcher<TValue, TSelected>(
8 fn,
9 options?,
10selector?): ReactBatcher<TValue, TSelected>;
11```
12
13Defined in: [batcher/useBatcher.ts:181](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/batcher/useBatcher.ts#L181)
14
15A React hook that creates and manages a Batcher instance.
16
17This is a lower-level hook that provides direct access to the Batcher'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
21The Batcher collects items and processes them in batches based on configurable conditions:
22- Maximum batch size
23- Time-based batching (process after X milliseconds)
24- Custom batch processing logic via getShouldExecute
25
26## State Management and Selector
27
28The hook uses TanStack Store for reactive state management. You can subscribe to state changes
29in two ways:
30
31**1. Using `batcher.Subscribe` HOC (Recommended for component tree subscriptions)**
32
33Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
34needing to pass a selector to the hook. This is ideal when you want to subscribe to state
35in child components.
36
37**2. Using the `selector` parameter (For hook-level subscriptions)**
38
39The `selector` parameter allows you to specify which state changes will trigger a re-render
40at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
41state changes occur.
42
43**By default, there will be no reactive state subscriptions** and you must opt-in to state
44tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
45re-renders and gives you full control over when your component updates.
46
47Available state properties:
48- `executionCount`: Number of batch executions that have been completed
49- `isEmpty`: Whether the batcher has no items to process
50- `isPending`: Whether the batcher is waiting for the timeout to trigger batch processing
51- `items`: Array of items currently queued for batch processing
52- `size`: Number of items currently in the batch queue
53- `status`: Current processing status ('idle' | 'pending')
54- `totalItemsProcessed`: Total number of items processed across all batches
55
56## Unmount behavior
57
58By default, the hook cancels any pending batch when the component unmounts.
59Use the `onUnmount` option to customize this. For example, to flush pending work instead:
60
61```tsx
62const batcher = useBatcher(fn, {
63 maxSize: 5,
64 wait: 2000,
65 onUnmount: (b) => b.flush()
66});
67```
68
69## Type Parameters
70
71### TValue
72
73`TValue`
74
75### TSelected
76
77`TSelected` = \{
78\}
79
80## Parameters
81
82### fn
83
84(`items`) => `void`
85
86### options?
87
88[`ReactBatcherOptions`](../interfaces/ReactBatcherOptions.md)\<`TValue`, `TSelected`\> = `{}`
89
90### selector?
91
92(`state`) => `TSelected`
93
94## Returns
95
96[`ReactBatcher`](../interfaces/ReactBatcher.md)\<`TValue`, `TSelected`\>
97
98## Example
99
100```tsx
101// Default behavior - no reactive state subscriptions
102const batcher = useBatcher<number>(
103 (items) => console.log('Processing batch:', items),
104 { maxSize: 5, wait: 2000 }
105);
106
107// Subscribe to state changes deep in component tree using Subscribe HOC
108<batcher.Subscribe selector={(state) => ({ size: state.size, isPending: state.isPending })}>
109 {({ size, isPending }) => (
110 <div>Batch: {size} items, {isPending ? 'Pending' : 'Ready'}</div>
111 )}
112</batcher.Subscribe>
113
114// Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)
115const batcher = useBatcher<number>(
116 (items) => console.log('Processing batch:', items),
117 { maxSize: 5, wait: 2000 },
118 (state) => ({
119 size: state.size,
120 isEmpty: state.isEmpty
121 })
122);
123
124// Opt-in to re-render when execution metrics change (optimized for stats display)
125const batcher = useBatcher<number>(
126 (items) => console.log('Processing batch:', items),
127 { maxSize: 5, wait: 2000 },
128 (state) => ({
129 executionCount: state.executionCount,
130 totalItemsProcessed: state.totalItemsProcessed
131 })
132);
133
134// Opt-in to re-render when processing state changes (optimized for loading indicators)
135const batcher = useBatcher<number>(
136 (items) => console.log('Processing batch:', items),
137 { maxSize: 5, wait: 2000 },
138 (state) => ({
139 isPending: state.isPending,
140 status: state.status
141 })
142);
143
144// Example with custom state management and batching
145const [items, setItems] = useState([]);
146
147const batcher = useBatcher<number>(
148 (items) => console.log('Processing batch:', items),
149 {
150 maxSize: 5,
151 wait: 2000,
152 onItemsChange: (batcher) => setItems(batcher.peekAllItems()),
153 getShouldExecute: (items) => items.length >= 3
154 }
155);
156
157// Add items to batch - they'll be processed when conditions are met
158batcher.addItem(1);
159batcher.addItem(2);
160batcher.addItem(3); // Triggers batch processing
161
162// Control the batcher
163batcher.cancel(); // Cancel the pending timer; queued items are retained
164batcher.flush(); // Process queued items immediately
165
166// Access the selected state (will be empty object {} unless selector provided)
167const { size, isPending } = batcher.state;
168```