Open History to see the last commit
1---
2title: Alpine Batching Guide
3id: batching
4---
5
6Batching collects items and passes them to one function as an array. A batch can run when it reaches a configured size, after no new items arrive for a configured wait, or when custom logic says it is ready.
7
8Batching reduces the number of operations by processing several items together. Unlike queuing, it does not call the wrapped function once for each item.
9
10## How batching works
11
12```text
13Batching (process every 3 items or after 2 quiet ticks)
14Timeline: [1 second per tick]
15Calls: ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
16Batch: [ABC] [] [DE] [] [FGH] []
17Executed: ✅ ✅ ✅
18 [======================================================]
19 ^ Items are grouped and processed together
20
21 [Size reached] [Wait elapsed] [Size reached]
22```
23
24Each execution receives a copy of the items currently collected. The batcher clears those items before calling the wrapped function.
25
26## When to use batching
27
28Choose batching when:
29
30- A bulk operation is more efficient than individual operations.
31- Network requests, database writes, or analytics events can be grouped.
32- A maximum batch size or quiet-period trigger matches the workload.
33- Individual item results are unnecessary.
34
35Choose another utility when:
36
37- Every item should run individually and in order. Use [queuing](./queuing.md).
38- Only the latest value matters. Use [debouncing](./debouncing.md).
39- Calls should be spaced over time. Use [throttling](./throttling.md).
40- Batch processing returns a Promise or needs retries and abort support. Use [async batching](./async-batching.md).
41
42## Choose an API
43
44- `createBatcher` for flush, cancel, collected items, and selected state
45
46Use the batcher's bound `addItem` method as an event handler. Keep the instance for `flush()`, `cancel()`, collected items, selected state, and dynamic options.
47
48## Alpine example
49
50Create one Pacer scope for each Alpine component and destroy it from the component's `destroy` method. The example imports application operations from `./api`.
51
52```ts
53import Alpine from 'alpinejs'
54import { createPacerScope } from '@tanstack/alpine-pacer'
55import { sendEvents } from './api'
56
57Alpine.data('example', () => {
58 const scope = createPacerScope()
59 const batcher = scope.createBatcher(
60 sendEvents,
61 { maxSize: 20, wait: 1000 },
62 (state) => ({ size: state.size, executionCount: state.executionCount }),
63 )
64 return {
65 batcher,
66 schedule() {
67 void batcher.addItem({ type: 'click' })
68 },
69 destroy() {
70 scope.destroy()
71 },
72 }
73})
74
75Alpine.start()
76```
77
78```html
79<div x-data="example">
80 <button @click="schedule">Track</button>
81 <output x-text="batcher.state.size"></output>
82</div>
83```
84
85The focused snippets below use the component-owned `scope` created above. Call their control methods from event handlers.
86
87## Choosing batch triggers
88
89### Batch size
90
91`maxSize` executes the batch as soon as the number of collected items reaches the limit.
92
93```ts
94const batcher = scope.createBatcher(processBatch, {
95 maxSize: 100,
96})
97```
98
99The default is `Infinity`, so a size trigger is disabled unless you provide one.
100
101### Wait time
102
103`wait` executes a batch after no new items arrive for the configured duration. Every added item restarts the timer.
104
105```ts
106const batcher = scope.createBatcher(processBatch, {
107 wait: 1000,
108})
109```
110
111The default is `Infinity`, so a time trigger is disabled unless you provide one. A continuous stream of items can keep restarting the timer. Combine `wait` with `maxSize` when a batch must eventually run under continuous traffic.
112
113### Custom trigger
114
115`getShouldExecute` runs after each item is added. Return `true` to execute the current batch immediately.
116
117```ts
118const batcher = createBatcher<number>(processBatch, {
119 getShouldExecute: (items) => items.includes(0),
120})
121
122batcher.addItem(4)
123batcher.addItem(0) // Executes [4, 0].
124```
125
126If several triggers are configured, the first one reached executes the batch.
127
128## Controlling collected items
129
130### Flush
131
132`flush()` clears the pending timer and executes all currently collected items. It does nothing when the batch is empty.
133
134```ts
135batcher.addItem('event-1')
136batcher.addItem('event-2')
137batcher.flush()
138```
139
140### Cancel
141
142`cancel()` clears the pending timer but keeps the collected items. A later item can schedule a new timer, or you can call `flush()`.
143
144```ts
145batcher.cancel()
146console.log(batcher.peekAllItems()) // Items are still present.
147```
148
149### Clear
150
151`clear()` removes all collected items. It does not clear the timer itself, although that timer has no items to execute unless more items are added.
152
153```ts
154batcher.clear()
155```
156
157### Reset
158
159`reset()` restores batch state and counters to their defaults. It does not cancel an already scheduled timer. Call `cancel()` before `reset()` when pending work must be discarded.
160
161```ts
162batcher.cancel()
163batcher.reset()
164```
165
166## Configuring and observing batches
167
168Use `setOptions()` to update future trigger behavior:
169
170```ts
171batcher.setOptions({
172 maxSize: 20,
173 wait: 500,
174})
175```
176
177Changing `wait` does not reschedule an existing timer. The next `addItem()` call replaces that timer using the current value.
178
179The `wait` option may be a function that receives the batcher instance:
180
181```ts
182const batcher = scope.createBatcher(processBatch, {
183 wait: (batcher) => (batcher.store.state.size > 10 ? 100 : 500),
184})
185```
186
187Use `onItemsChange` to observe collection changes and `onExecute` to observe completed batch calls:
188
189```ts
190const batcher = scope.createBatcher(processBatch, {
191 maxSize: 10,
192 onItemsChange: (batcher) => {
193 console.log('Collected:', batcher.store.state.size)
194 },
195 onExecute: (items, batcher) => {
196 console.log('Processed:', items)
197 console.log('Batches:', batcher.store.state.executionCount)
198 },
199})
200```
201
202Do not use `started` to pause a batcher. It is currently a no-op, so every `addItem()` call evaluates the configured triggers.
203
204## Alpine lifecycle
205
206The adapter cancels the pending wait timer while retaining collected items when its owner is destroyed. Providing `onUnmount` replaces that default cleanup, so a custom callback must perform every required lifecycle action. When custom cleanup flushes work, remember that user callbacks can run while the component is being destroyed.
207
208## Reactive state
209
210The adapter subscribes only to the state returned by the selector argument. Without a selector, the adapter state is empty. Create the utility in its owning scope and select fields used by `x-text` and `x-bind`:
211
212```ts
213const batcher = scope.createBatcher(
214 processBatch,
215 { maxSize: 20, wait: 1000 },
216 (state) => ({
217 size: state.size,
218 isPending: state.isPending,
219 }),
220)
221
222console.log(batcher.state.size, batcher.state.isPending)
223```
224
225Use `utility.subscribe(childScope, selector)` for an independently subscribed child scope. It returns a selected-state getter and cleans up with that child scope.
226
227Option functions and lifecycle callbacks receive the underlying public utility instance. The `.store.state` reads inside those callbacks in the examples above are supported. Rendering code should read the selected adapter state shown here.
228
229To restore selected state that your app has persisted, pass a partial snapshot through `initialState`. It is merged with the defaults. Restore only durable fields. Pending timers are not restored.
230
231Commonly useful state includes:
232
233- `items`: Items currently collected.
234- `size`: Number of collected items.
235- `isEmpty`: Whether the batch is empty.
236- `isPending`: Whether a wait timer is active.
237- `executionCount`: Completed batch executions.
238- `totalItemsProcessed`: Items passed to completed batch executions.
239- `status`: `'idle'` or `'pending'`.
240
241See the [Alpine API reference](../reference/index.md) for adapter signatures and the public core reference for complete option and state types.