Open History to see the last commit
1---
2title: Alpine Quick Start
3id: quick-start
4redirectFrom:
5 - framework/alpine/adapter
6---
7
8TanStack Pacer controls when your functions run. The Alpine adapter, `@tanstack/alpine-pacer`, creates Pacer utilities that belong to a scope. The scope tracks option changes, updates your templates when selected state changes, and cleans up every utility it owns when you destroy it.
9
10This page starts with a debounced search input, then covers the patterns most apps need next.
11
12## Installation
13
14```sh
15npm install @tanstack/alpine-pacer
16```
17
18The adapter re-exports everything from `@tanstack/pacer`, so you do not need to install the core package. See [Installation](../../installation.md) for other package managers.
19
20## Your first debouncer
21
22The component below is complete. The input updates on every keystroke. The debounced query updates 500 ms after the user stops typing.
23
24```ts
25import Alpine from 'alpinejs'
26import { createPacerScope } from '@tanstack/alpine-pacer'
27
28Alpine.data('search', () => {
29 const scope = createPacerScope()
30
31 return {
32 query: '',
33 debouncedQuery: () => '',
34 init() {
35 ;[this.debouncedQuery] = scope.createDebouncedValue(() => this.query, {
36 wait: 500,
37 })
38 },
39 destroy() {
40 scope.destroy()
41 },
42 }
43})
44
45Alpine.start()
46```
47
48```html
49<div x-data="search">
50 <input x-model="query" placeholder="Search..." />
51 <p>Searching for: <span x-text="debouncedQuery()"></span></p>
52</div>
53```
54
55Create utilities in `init()`, where `this` is Alpine's reactive proxy. `createDebouncedValue` takes a getter, `() => this.query`, so it can track changes. It returns a getter too, so call `debouncedQuery()` to read it. Destroying the scope in `destroy()` cancels any pending update.
56
57Pass the debounced value to your data fetching instead of `query`, and a fast typist sends one request instead of one per keystroke.
58
59### Skip the scope with the `$pacer` magic
60
61If you install `pacerPlugin`, every component gets a `$pacer` scope that Alpine destroys with the element. You no longer need `createPacerScope` or `destroy()`. The adapter does not add `$pacer` to Alpine's TypeScript types, so this example is JavaScript:
62
63```js
64import Alpine from 'alpinejs'
65import { pacerPlugin } from '@tanstack/alpine-pacer'
66
67Alpine.plugin(pacerPlugin)
68
69Alpine.data('search', () => ({
70 query: '',
71 debouncedQuery: () => '',
72 init() {
73 ;[this.debouncedQuery] = this.$pacer.createDebouncedValue(
74 () => this.query,
75 { wait: 500 },
76 )
77 },
78}))
79```
80
81The rest of this page uses an explicit scope. Every scope method is also available on `$pacer`.
82
83## Pick a method
84
85Every utility comes in several shapes. They share one engine and differ in what they hand back to you. For debouncing:
86
87| Scope method | Returns | Use it when |
88| ---------------------- | ------------------------------ | ------------------------------------------------------------- |
89| `createDebouncedValue` | `[debouncedValue, debouncer]` | You already have a property and want a lagging copy |
90| `createDebouncedState` | `[value, setValue, debouncer]` | You want a value with a debounced setter |
91| `createDebouncer` | The debouncer instance | You need `maybeExecute`, `flush`, `cancel`, or reactive state |
92
93The other utilities follow the same naming pattern:
94
95| Utility | Instance method | Async instance method | Guide |
96| ------------- | ------------------- | ------------------------ | ------------------------------------------ |
97| Debouncing | `createDebouncer` | `createAsyncDebouncer` | [Debouncing](./guides/debouncing.md) |
98| Throttling | `createThrottler` | `createAsyncThrottler` | [Throttling](./guides/throttling.md) |
99| Rate limiting | `createRateLimiter` | `createAsyncRateLimiter` | [Rate Limiting](./guides/rate-limiting.md) |
100| Queuing | `createQueuer` | `createAsyncQueuer` | [Queuing](./guides/queuing.md) |
101| Batching | `createBatcher` | `createAsyncBatcher` | [Batching](./guides/batching.md) |
102
103Not sure which utility you need? Read [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md).
104
105## Common patterns
106
107### Control the debouncer directly
108
109`createDebouncer` returns the instance. Call `maybeExecute` from your event handler, and use `flush` or `cancel` when the user acts before the timer fires.
110
111```ts
112import Alpine from 'alpinejs'
113import { createPacerScope } from '@tanstack/alpine-pacer'
114import type { AlpineDebouncer } from '@tanstack/alpine-pacer'
115
116Alpine.data('draftEditor', () => {
117 const scope = createPacerScope()
118
119 return {
120 draft: '',
121 saver: null as AlpineDebouncer<
122 (text: string) => void,
123 { isPending: boolean }
124 > | null,
125 init() {
126 this.saver = scope.createDebouncer(
127 (text: string) => saveDraft(text),
128 { wait: 1000 },
129 (state) => ({ isPending: state.isPending }),
130 )
131 },
132 onInput() {
133 this.saver!.maybeExecute(this.draft)
134 },
135 destroy() {
136 scope.destroy()
137 },
138 }
139})
140```
141
142```html
143<div x-data="draftEditor">
144 <textarea x-model="draft" @input="onInput"></textarea>
145 <button @click="saver.flush()">Save now</button>
146 <button @click="saver.cancel()">Discard</button>
147 <p x-show="saver.state.isPending">Unsaved changes...</p>
148</div>
149```
150
151### Select the state you render
152
153The last argument is a selector. Read the selected fields from `saver.state` in your template. Without a selector, it is `{}` and never changes. Select only the fields your template reads.
154
155A child component can subscribe to the same utility with its own selector. Call `subscribe` with the child's scope. It returns a reactive getter for the selection and leaves the owner's selection unchanged:
156
157```ts
158const status = saver.subscribe(childScope, (state) => ({
159 isPending: state.isPending,
160}))
161
162// In the child's template or a getter
163status().isPending
164```
165
166Destroy the child scope in the child component's `destroy()` hook to release the subscription. Each utility's guide lists the state fields it exposes.
167
168### Make options reactive
169
170A plain options object is read once. To make an option follow a component property, pass a factory that returns the options:
171
172```ts
173init() {
174 this.searcher = scope.createDebouncer(search, () => ({ wait: this.wait }))
175}
176```
177
178Property getters such as `get wait() { return this.wait }` work too.
179
180When an option changes, the adapter updates the same utility. Pending work and state survive. A changed `wait` applies to the next call. It does not reschedule a timer that is already running. Setting `enabled` to `false` cancels pending work. `key`, `initialState`, and `initialItems` apply only when the utility is created.
181
182### Run async work
183
184The async methods await your function, track execution state, and report errors. This search debounces the request and shows a loading state:
185
186```ts
187import Alpine from 'alpinejs'
188import { createPacerScope } from '@tanstack/alpine-pacer'
189import type { AlpineAsyncDebouncer } from '@tanstack/alpine-pacer'
190
191type Search = (term: string) => Promise<Array<SearchResult>>
192
193Alpine.data('asyncSearch', () => {
194 const scope = createPacerScope()
195
196 return {
197 results: [] as Array<SearchResult>,
198 searcher: null as AlpineAsyncDebouncer<
199 Search,
200 { isExecuting: boolean }
201 > | null,
202 init() {
203 this.searcher = scope.createAsyncDebouncer(
204 async (term: string) => {
205 const data = await fetchSearchResults(term)
206 this.results = data
207 return data
208 },
209 {
210 wait: 300,
211 onError: (error) => console.error('Search failed:', error),
212 },
213 (state) => ({ isExecuting: state.isExecuting }),
214 )
215 },
216 destroy() {
217 scope.destroy()
218 },
219 }
220})
221```
222
223```html
224<div x-data="asyncSearch">
225 <input @input="searcher.maybeExecute($event.target.value)" />
226 <p x-show="searcher.state.isExecuting">Loading...</p>
227 <ul>
228 <template x-for="result in results" :key="result.id">
229 <li x-text="result.title"></li>
230 </template>
231 </ul>
232</div>
233```
234
235`maybeExecute` returns a promise that resolves with your function's result. The async utilities also support retries and cancellation through an `AbortSignal`. See the [Async Debouncing Guide](./guides/async-debouncing.md).
236
237### Limit how often an action runs
238
239A rate limiter allows a fixed number of calls per window and rejects the rest:
240
241```ts
242init() {
243 this.limiter = scope.createRateLimiter(
244 (message: string) => sendMessage(message),
245 {
246 limit: 5,
247 window: 60_000,
248 onReject: (limiter) =>
249 alert(`Slow down. Try again in ${limiter.getMsUntilNextWindow()} ms.`),
250 },
251 (state) => ({ rejectionCount: state.rejectionCount }),
252 )
253}
254```
255
256```html
257<button @click="limiter.maybeExecute('Hello')">Send</button>
258<p>Rejected: <span x-text="limiter.state.rejectionCount"></span></p>
259```
260
261### Process items in order
262
263A queuer keeps every item and processes them in order. With `createAsyncQueuer`, `concurrency` sets how many run at once:
264
265```ts
266init() {
267 this.queue = scope.createAsyncQueuer(
268 async (file: File) => uploadFile(file),
269 { concurrency: 3 },
270 (state) => ({ size: state.size, activeItems: state.activeItems }),
271 )
272},
273onFiles(event: Event) {
274 const files = (event.target as HTMLInputElement).files
275 for (const file of files ?? []) this.queue!.addItem(file)
276},
277```
278
279```html
280<input type="file" multiple @change="onFiles" />
281<p>
282 Uploading <span x-text="queue.state.activeItems.length"></span>, waiting
283 <span x-text="queue.state.size"></span>
284</p>
285```
286
287## Set default options
288
289Pass default options to `createPacerScope`. Every utility created through that scope uses them, and options passed to a utility override them.
290
291```ts
292const scope = createPacerScope({
293 debouncer: { wait: 500 },
294 asyncQueuer: { concurrency: 3 },
295 rateLimiter: { limit: 5, window: 60_000 },
296})
297```
298
299To read component properties in the defaults, pass a factory that returns the object.
300
301To share options between specific utilities instead, define them once with an option helper. Helpers such as `debouncerOptions` return the object you pass in, typed for that utility:
302
303```ts
304import { debouncerOptions } from '@tanstack/alpine-pacer'
305
306const searchOptions = debouncerOptions({ wait: 500, leading: false })
307
308// In init()
309this.searcher = scope.createDebouncer(search, {
310 ...searchOptions,
311 key: 'search',
312})
313```
314
315## Control cleanup
316
317When the scope is destroyed, debouncers, throttlers, and batchers cancel pending work, and queuers stop processing. Async utilities also abort active work. To keep work instead, pass `onUnmount`. It replaces the default cleanup:
318
319```ts
320this.saver = scope.createDebouncer(saveDraft, {
321 wait: 1000,
322 onUnmount: (debouncer) => debouncer.flush(),
323})
324```
325
326## Set up devtools
327
328Install the devtools packages:
329
330```sh
331npm install @tanstack/devtools @tanstack/pacer-devtools
332```
333
334Alpine uses the framework-independent devtools. Mount `TanStackDevtoolsCore` with `plugins: [pacerDevtoolsPlugin()]` from a dedicated Alpine component, and unmount it in that component's `destroy()` hook. The [Alpine devtools setup](../../devtools.md#alpine) has the full code.
335
336A utility appears in the Pacer panel only when you give it a `key` option.
337
338## Next steps
339
340- [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md) compares all five utilities.
341- The [Debouncing](./guides/debouncing.md), [Throttling](./guides/throttling.md), [Rate Limiting](./guides/rate-limiting.md), [Queuing](./guides/queuing.md), and [Batching](./guides/batching.md) guides cover each utility's options and state. Each has an async counterpart.
342- The [Alpine API Reference](./reference/index.md) lists every function and its options.
343- The [Alpine examples](./examples/createDebouncer) are runnable apps for each utility.