Skip to content
Source
Sign inSign up
TanStack/pacer
Open History to see the last commit

quick-start.md

303 lines10.6 KB

1---
2title: Vue Quick Start
3id: quick-start
4redirectFrom:
5 - framework/vue/adapter
6---
7​
8TanStack Pacer controls when your functions run. The Vue adapter, `@tanstack/vue-pacer`, wraps each Pacer utility in a composable. Call composables during component setup or inside an active effect scope. The utility cleans up when the scope is disposed and exposes the state you select as a ref.
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/vue-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. `debouncedQuery` updates 500 ms after the user stops typing.
23​
24```vue
25<script setup lang="ts">
26import { ref } from 'vue'
27import { useDebouncedValue } from '@tanstack/vue-pacer'
28​
29const query = ref('')
30const [debouncedQuery] = useDebouncedValue(query, { wait: 500 })
31</script>
32​
33<template>
34 <input v-model="query" placeholder="Search..." />
35 <p>Searching for: {{ debouncedQuery }}</p>
36</template>
37```
38​
39`useDebouncedValue` accepts a ref or a getter such as `() => props.query`. It returns a read-only ref. Pass `debouncedQuery` to your data fetching instead of `query`, and a fast typist sends one request instead of one per keystroke.
40​
41## Pick a composable
42​
43Every utility comes in several shapes. They share one engine and differ in what they hand back to you. For debouncing:
44​
45| Composable | Returns | Use it when |
46| ------------------- | ------------------------------ | ------------------------------------------------------------- |
47| `useDebouncedValue` | `[debouncedValue, debouncer]` | You already have a ref and want a lagging copy |
48| `useDebouncedState` | `[value, setValue, debouncer]` | You want a ref with a debounced setter |
49| `useDebouncer` | The debouncer instance | You need `maybeExecute`, `flush`, `cancel`, or reactive state |
50​
51The other utilities follow the same naming pattern:
52​
53| Utility | Instance composable | Async instance composable | Guide |
54| ------------- | ------------------- | ------------------------- | ------------------------------------------ |
55| Debouncing | `useDebouncer` | `useAsyncDebouncer` | [Debouncing](./guides/debouncing.md) |
56| Throttling | `useThrottler` | `useAsyncThrottler` | [Throttling](./guides/throttling.md) |
57| Rate limiting | `useRateLimiter` | `useAsyncRateLimiter` | [Rate Limiting](./guides/rate-limiting.md) |
58| Queuing | `useQueuer` | `useAsyncQueuer` | [Queuing](./guides/queuing.md) |
59| Batching | `useBatcher` | `useAsyncBatcher` | [Batching](./guides/batching.md) |
60​
61Not sure which utility you need? Read [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md).
62​
63## Common patterns
64​
65### Control the debouncer directly
66​
67`useDebouncer` returns the instance. Call `maybeExecute` from your event handler, and use `flush` or `cancel` when the user acts before the timer fires.
68​
69```vue
70<script setup lang="ts">
71import { ref } from 'vue'
72import { useDebouncer } from '@tanstack/vue-pacer'
73​
74const draft = ref('')
75​
76const saver = useDebouncer(
77 (text: string) => saveDraft(text),
78 { wait: 1000 },
79 (state) => ({ isPending: state.isPending }),
81const saverState = saver.state
82​
83function onInput(event: Event) {
84 draft.value = (event.target as HTMLTextAreaElement).value
85 saver.maybeExecute(draft.value)
87</script>
88​
89<template>
90 <textarea :value="draft" @input="onInput" />
91 <button @click="saver.flush()">Save now</button>
92 <button @click="saver.cancel()">Discard</button>
93 <p v-if="saverState.isPending">Unsaved changes...</p>
94</template>
95```
96​
97### Select the state you render
98​
99The third argument is a selector. `saver.state` is a ref, so read `saver.state.value` in script. Without a selector, it holds `{}` and never changes. Select only the fields you render.
100​
101Vue templates unwrap top-level refs only. `saver.state.isPending` in a template reads a property of the ref object, not of its value. Assign the ref to a top-level variable, as `saverState` does above.
102​
103To read state in one part of the template without a selector on the utility, use the `Subscribe` component. Its slot receives the selected state, and the owning component does not re-render:
104​
105```vue
106<saver.Subscribe
107 :selector="(state) => ({ isPending: state.isPending })"
108 v-slot="{ isPending }"
110 <span v-if="isPending">Saving...</span>
111</saver.Subscribe>
112```
113​
114Each utility's guide lists the state fields it exposes.
115​
116### Make options reactive
117​
118A plain options object is read once. To make an option follow a ref or a prop, pass a factory that returns the options:
119​
120```ts
121const props = defineProps<{ wait: number }>()
122​
123const debouncer = useDebouncer(search, () => ({ wait: props.wait }))
124```
125​
126Property getters such as `get wait() { return props.wait }` work too. A ref placed inside a plain options object is not unwrapped.
127​
128When 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.
129​
130### Run async work
131​
132The async composables await your function, track execution state, and report errors. This search debounces the request and shows a loading state:
133​
134```vue
135<script setup lang="ts">
136import { ref } from 'vue'
137import { useAsyncDebouncer } from '@tanstack/vue-pacer'
138​
139const results = ref<Array<SearchResult>>([])
140​
141const searcher = useAsyncDebouncer(
142 async (term: string) => {
143 const data = await fetchSearchResults(term)
144 results.value = data
145 return data
146 },
147 {
148 wait: 300,
149 onError: (error) => console.error('Search failed:', error),
150 },
151 (state) => ({ isExecuting: state.isExecuting }),
153const searcherState = searcher.state
154</script>
155​
156<template>
157 <input
158 @input="searcher.maybeExecute(($event.target as HTMLInputElement).value)"
159 />
160 <p v-if="searcherState.isExecuting">Loading...</p>
161 <ul>
162 <li v-for="result in results" :key="result.id">{{ result.title }}</li>
163 </ul>
164</template>
165```
166​
167`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).
168​
169### Limit how often an action runs
170​
171A rate limiter allows a fixed number of calls per window and rejects the rest:
172​
173```vue
174<script setup lang="ts">
175import { useRateLimiter } from '@tanstack/vue-pacer'
176​
177const limiter = useRateLimiter(
178 (message: string) => sendMessage(message),
179 {
180 limit: 5,
181 window: 60_000,
182 onReject: (limiter) =>
183 alert(`Slow down. Try again in ${limiter.getMsUntilNextWindow()} ms.`),
184 },
185 (state) => ({ rejectionCount: state.rejectionCount }),
187const limiterState = limiter.state
188</script>
189​
190<template>
191 <button @click="limiter.maybeExecute('Hello')">Send</button>
192 <p>Rejected: {{ limiterState.rejectionCount }}</p>
193</template>
194```
195​
196### Process items in order
197​
198A queuer keeps every item and processes them in order. With `useAsyncQueuer`, `concurrency` sets how many run at once:
199​
200```vue
201<script setup lang="ts">
202import { useAsyncQueuer } from '@tanstack/vue-pacer'
203​
204const queue = useAsyncQueuer(
205 async (file: File) => uploadFile(file),
206 { concurrency: 3 },
207 (state) => ({ size: state.size, activeItems: state.activeItems }),
209const queueState = queue.state
210​
211function onFiles(event: Event) {
212 const files = (event.target as HTMLInputElement).files
213 for (const file of files ?? []) queue.addItem(file)
215</script>
216​
217<template>
218 <input type="file" multiple @change="onFiles" />
219 <p>
220 Uploading {{ queueState.activeItems.length }}, waiting
221 {{ queueState.size }}
222 </p>
223</template>
224```
225​
226## Set default options
227​
228`PacerProvider` sets default options for every Pacer composable in its subtree. Options passed to a composable override the defaults.
229​
230```vue
231<script setup lang="ts">
232import { PacerProvider } from '@tanstack/vue-pacer'
233</script>
234​
235<template>
236 <PacerProvider
237 :default-options="{
238 debouncer: { wait: 500 },
239 asyncQueuer: { concurrency: 3 },
240 rateLimiter: { limit: 5, window: 60_000 },
241 }"
242 >
243 <AppContent />
244 </PacerProvider>
245</template>
246```
247​
248To set defaults from a component's setup without a wrapper, call `providePacerOptions` with the same object or a factory that returns it.
249​
250To share options between specific composables instead, define them once with an option helper. Helpers such as `debouncerOptions` return the object you pass in, typed for that utility:
251​
252```ts
253import { debouncerOptions, useDebouncer } from '@tanstack/vue-pacer'
254​
255const searchOptions = debouncerOptions({ wait: 500, leading: false })
256​
257const debouncer = useDebouncer(search, { ...searchOptions, key: 'search' })
258```
259​
260## Control cleanup
261​
262When the scope is disposed, 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:
263​
264```ts
265const saver = useDebouncer(saveDraft, {
266 wait: 1000,
267 onUnmount: (debouncer) => debouncer.flush(),
268})
269```
270​
271## Set up devtools
272​
273Install the devtools packages:
274​
275```sh
276npm install @tanstack/vue-devtools @tanstack/vue-pacer-devtools
277```
278​
279Render the devtools once in your root component:
280​
281```vue
282<script setup lang="ts">
283import { TanStackDevtools } from '@tanstack/vue-devtools'
284import { pacerDevtoolsPlugin } from '@tanstack/vue-pacer-devtools'
285​
286const dev = import.meta.env.DEV
287const plugins = [pacerDevtoolsPlugin()]
288</script>
289​
290<template>
291 <AppContent />
292 <TanStackDevtools v-if="dev" :plugins="plugins" />
293</template>
294```
295​
296A utility appears in the Pacer panel only when you give it a `key` option. See [Devtools](../../devtools.md) for production builds.
297​
298## Next steps
299​
300- [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md) compares all five utilities.
301- 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.
302- The [Vue API Reference](./reference/index.md) lists every composable and its options.
303- The [Vue examples](./examples/useDebouncer) are runnable apps for each composable.