Open History to see the last commit
1---
2title: Lit Quick Start
3id: quick-start
4redirectFrom:
5 - framework/lit/adapter
6---
7
8TanStack Pacer controls when your functions run. The Lit adapter, `@tanstack/lit-pacer`, wraps each Pacer utility in a `create*` function that takes your element as its first argument. The function registers a reactive controller on the element. The controller re-renders the element when selected state changes and cleans up pending work when the element disconnects.
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/lit-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
20The examples on this page declare reactive properties with `static properties` and class field initializers. For Lit to install its property accessors, set `"useDefineForClassFields": false` in your `tsconfig.json`.
21
22## Your first debouncer
23
24The element below is complete. The input updates on every keystroke. The debounced query updates 500 ms after the user stops typing.
25
26```ts
27import { LitElement, html } from 'lit'
28import { createDebouncedValue } from '@tanstack/lit-pacer'
29
30class SearchBox extends LitElement {
31 static properties = { query: { state: true } }
32 query = ''
33
34 debounced = createDebouncedValue(this, () => this.query, { wait: 500 })
35
36 override render() {
37 const [debouncedQuery] = this.debounced
38 return html`
39 <input
40 .value=${this.query}
41 @input=${(e: Event) => {
42 this.query = (e.target as HTMLInputElement).value
43 }}
44 placeholder="Search..."
45 />
46 <p>Searching for: ${debouncedQuery()}</p>
47 `
48 }
49}
50
51customElements.define('search-box', SearchBox)
52```
53
54`createDebouncedValue` takes a getter, `() => this.query`, and reads it each time the element updates. It returns `[debouncedValue, debouncer]`, where `debouncedValue` is a getter. Pass the debounced value to your data fetching instead of `query`, and a fast typist sends one request instead of one per keystroke.
55
56## Pick a function
57
58Every utility comes in several shapes. They share one engine and differ in what they hand back to you. For debouncing:
59
60| Function | Returns | Use it when |
61| ---------------------- | ------------------------------ | ------------------------------------------------------------- |
62| `createDebouncedValue` | `[debouncedValue, debouncer]` | You already have a property and want a lagging copy |
63| `createDebouncedState` | `[value, setValue, debouncer]` | You want a value with a debounced setter |
64| `createDebouncer` | The debouncer instance | You need `maybeExecute`, `flush`, `cancel`, or reactive state |
65
66The other utilities follow the same naming pattern:
67
68| Utility | Instance function | Async instance function | Guide |
69| ------------- | ------------------- | ------------------------ | ------------------------------------------ |
70| Debouncing | `createDebouncer` | `createAsyncDebouncer` | [Debouncing](./guides/debouncing.md) |
71| Throttling | `createThrottler` | `createAsyncThrottler` | [Throttling](./guides/throttling.md) |
72| Rate limiting | `createRateLimiter` | `createAsyncRateLimiter` | [Rate Limiting](./guides/rate-limiting.md) |
73| Queuing | `createQueuer` | `createAsyncQueuer` | [Queuing](./guides/queuing.md) |
74| Batching | `createBatcher` | `createAsyncBatcher` | [Batching](./guides/batching.md) |
75
76Each instance function also has a controller class, such as `DebouncerController`, if you prefer to construct controllers yourself. The controller exposes the utility as `.pacer` and the selected state as `.state`.
77
78Not sure which utility you need? Read [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md).
79
80## Common patterns
81
82### Control the debouncer directly
83
84`createDebouncer` returns the instance. Call `maybeExecute` from your event handler, and use `flush` or `cancel` when the user acts before the timer fires.
85
86```ts
87import { LitElement, html } from 'lit'
88import { createDebouncer } from '@tanstack/lit-pacer'
89
90class DraftEditor extends LitElement {
91 static properties = { draft: { state: true } }
92 draft = ''
93
94 saver = createDebouncer(
95 this,
96 (text: string) => saveDraft(text),
97 { wait: 1000 },
98 (state) => ({ isPending: state.isPending }),
99 )
100
101 onInput = (e: Event) => {
102 this.draft = (e.target as HTMLTextAreaElement).value
103 this.saver.maybeExecute(this.draft)
104 }
105
106 override render() {
107 return html`
108 <textarea .value=${this.draft} @input=${this.onInput}></textarea>
109 <button @click=${() => this.saver.flush()}>Save now</button>
110 <button @click=${() => this.saver.cancel()}>Discard</button>
111 ${this.saver.state.isPending ? html`<p>Unsaved changes...</p>` : null}
112 `
113 }
114}
115
116customElements.define('draft-editor', DraftEditor)
117```
118
119### Select the state you render
120
121The last argument is a selector. Read the selected fields from `this.saver.state`. Without a selector, it is `{}` and never changes. Select only the fields you render, because each change to the selection requests an update of the element.
122
123A child element can subscribe to the same utility with its own selector. Call `subscribe` once, passing the child element. It returns a getter for the selection, and only the child updates when the selection changes. The subscription is released when the child disconnects and restored when it reconnects.
124
125```ts
126const status = saver.subscribe(childElement, (state) => ({
127 isPending: state.isPending,
128}))
129
130// In the child's render method
131status().isPending
132```
133
134Each utility's guide lists the state fields it exposes.
135
136### Make options reactive
137
138To make an option follow a reactive property, pass a factory that returns the options. The controller calls it before each update of the element:
139
140```ts
141class SearchBox extends LitElement {
142 static properties = { wait: { type: Number } }
143 wait = 300
144
145 searcher = createDebouncer(this, search, () => ({ wait: this.wait }))
146}
147```
148
149Property getters such as `get wait() { return this.wait }` work too. A plain object such as `{ wait: this.wait }` reads the property once.
150
151When 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.
152
153### Run async work
154
155The async functions await your function, track execution state, and report errors. This search debounces the request and shows a loading state:
156
157```ts
158import { LitElement, html } from 'lit'
159import { createAsyncDebouncer } from '@tanstack/lit-pacer'
160
161class AsyncSearch extends LitElement {
162 static properties = { results: { state: true } }
163 results: Array<SearchResult> = []
164
165 searcher = createAsyncDebouncer(
166 this,
167 async (term: string) => {
168 const data = await fetchSearchResults(term)
169 this.results = data
170 return data
171 },
172 {
173 wait: 300,
174 onError: (error) => console.error('Search failed:', error),
175 },
176 (state) => ({ isExecuting: state.isExecuting }),
177 )
178
179 override render() {
180 return html`
181 <input
182 @input=${(e: Event) =>
183 this.searcher.maybeExecute((e.target as HTMLInputElement).value)}
184 />
185 ${this.searcher.state.isExecuting ? html`<p>Loading...</p>` : null}
186 <ul>
187 ${this.results.map((result) => html`<li>${result.title}</li>`)}
188 </ul>
189 `
190 }
191}
192
193customElements.define('async-search', AsyncSearch)
194```
195
196`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).
197
198### Limit how often an action runs
199
200A rate limiter allows a fixed number of calls per window and rejects the rest:
201
202```ts
203import { LitElement, html } from 'lit'
204import { createRateLimiter } from '@tanstack/lit-pacer'
205
206class SendButton extends LitElement {
207 limiter = createRateLimiter(
208 this,
209 (message: string) => sendMessage(message),
210 {
211 limit: 5,
212 window: 60_000,
213 onReject: (limiter) =>
214 alert(`Slow down. Try again in ${limiter.getMsUntilNextWindow()} ms.`),
215 },
216 (state) => ({ rejectionCount: state.rejectionCount }),
217 )
218
219 override render() {
220 return html`
221 <button @click=${() => this.limiter.maybeExecute('Hello')}>Send</button>
222 <p>Rejected: ${this.limiter.state.rejectionCount}</p>
223 `
224 }
225}
226
227customElements.define('send-button', SendButton)
228```
229
230### Process items in order
231
232A queuer keeps every item and processes them in order. With `createAsyncQueuer`, `concurrency` sets how many run at once:
233
234```ts
235import { LitElement, html } from 'lit'
236import { createAsyncQueuer } from '@tanstack/lit-pacer'
237
238class Uploader extends LitElement {
239 queue = createAsyncQueuer(
240 this,
241 async (file: File) => uploadFile(file),
242 { concurrency: 3 },
243 (state) => ({ size: state.size, activeItems: state.activeItems }),
244 )
245
246 onFiles = (e: Event) => {
247 const files = (e.target as HTMLInputElement).files
248 for (const file of files ?? []) this.queue.addItem(file)
249 }
250
251 override render() {
252 const { activeItems, size } = this.queue.state
253 return html`
254 <input type="file" multiple @change=${this.onFiles} />
255 <p>Uploading ${activeItems.length}, waiting ${size}</p>
256 `
257 }
258}
259
260customElements.define('file-uploader', Uploader)
261```
262
263## Set default options
264
265Call `providePacerOptions(host, defaults)` in an element's constructor or field initializer. The defaults apply to Pacer utilities on that element and on its descendant elements, including across shadow roots. The nearest provider wins, and options passed to a utility override the defaults.
266
267```ts
268import { LitElement, html } from 'lit'
269import { providePacerOptions } from '@tanstack/lit-pacer'
270
271class AppRoot extends LitElement {
272 constructor() {
273 super()
274 providePacerOptions(this, {
275 debouncer: { wait: 500 },
276 asyncQueuer: { concurrency: 3 },
277 rateLimiter: { limit: 5, window: 60_000 },
278 })
279 }
280
281 override render() {
282 return html`<slot></slot>`
283 }
284}
285```
286
287To read reactive properties of the provider element, pass a factory instead of an object. Descendants receive the new defaults when the provider updates.
288
289To 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:
290
291```ts
292import { createDebouncer, debouncerOptions } from '@tanstack/lit-pacer'
293
294const searchOptions = debouncerOptions({ wait: 500, leading: false })
295
296// In an element class
297searcher = createDebouncer(this, search, { ...searchOptions, key: 'search' })
298```
299
300## Control cleanup
301
302When the element disconnects, debouncers, throttlers, and batchers cancel pending work, and queuers stop processing. Async utilities also abort active work. If the element reconnects, the same utility subscribes again.
303
304To keep work instead, pass `onUnmount`. It replaces the default cleanup:
305
306```ts
307saver = createDebouncer(this, saveDraft, {
308 wait: 1000,
309 onUnmount: (debouncer) => debouncer.flush(),
310})
311```
312
313## Set up devtools
314
315Install the devtools packages:
316
317```sh
318npm install @tanstack/devtools @tanstack/pacer-devtools
319```
320
321Lit uses the framework-independent devtools. Mount `TanStackDevtoolsCore` with `plugins: [pacerDevtoolsPlugin()]` once in your application, and unmount it when your root element disconnects. The [Lit devtools setup](../../devtools.md#lit) has the full mount and cleanup code.
322
323A utility appears in the Pacer panel only when you give it a `key` option.
324
325## Next steps
326
327- [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md) compares all five utilities.
328- 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.
329- The [Lit API Reference](./reference/index.md) lists every function, controller, and option.
330- The [Lit examples](./examples/createDebouncer) are runnable apps for each function.