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