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

quick-start.md

320 lines10.4 KB

1---
2title: Preact Quick Start
3id: quick-start
4redirectFrom:
5 - framework/preact/adapter
6---
7​
8TanStack Pacer controls when your functions run. The Preact adapter, `@tanstack/preact-pacer`, wraps each Pacer utility in a hook. The hook keeps one utility instance across renders, cancels pending work when the component unmounts, and re-renders only for the state you select.
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/preact-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```tsx
25import { useState } from 'preact/hooks'
26import { useDebouncedValue } from '@tanstack/preact-pacer'
27​
28export function Search() {
29 const [query, setQuery] = useState('')
30 const [debouncedQuery] = useDebouncedValue(query, { wait: 500 })
31​
32 return (
33 <div>
34 <input
35 value={query}
36 onInput={(e) => setQuery(e.currentTarget.value)}
37 placeholder="Search..."
38 />
39 <p>Searching for: {debouncedQuery}</p>
40 </div>
41 )
43```
44​
45Pass `debouncedQuery` to your data fetching instead of `query`, and a fast typist sends one request instead of one per keystroke.
46​
47## Pick a hook
48​
49Every utility comes in several shapes. They share one engine and differ in what they hand back to you. For debouncing:
50​
51| Hook | Returns | Use it when |
52| ---------------------- | ------------------------------ | --------------------------------------------------------- |
53| `useDebouncedCallback` | A debounced function | You only need to call the function |
54| `useDebouncedValue` | `[debouncedValue, debouncer]` | You already have a value in state and want a lagging copy |
55| `useDebouncedState` | `[value, setValue, debouncer]` | You want `useState` with a debounced setter |
56| `useDebouncer` | The debouncer instance | You need `flush`, `cancel`, or reactive state |
57​
58The other utilities follow the same naming pattern:
59​
60| Utility | Instance hook | Async instance hook | Guide |
61| ------------- | ---------------- | --------------------- | ------------------------------------------ |
62| Debouncing | `useDebouncer` | `useAsyncDebouncer` | [Debouncing](./guides/debouncing.md) |
63| Throttling | `useThrottler` | `useAsyncThrottler` | [Throttling](./guides/throttling.md) |
64| Rate limiting | `useRateLimiter` | `useAsyncRateLimiter` | [Rate Limiting](./guides/rate-limiting.md) |
65| Queuing | `useQueuer` | `useAsyncQueuer` | [Queuing](./guides/queuing.md) |
66| Batching | `useBatcher` | `useAsyncBatcher` | [Batching](./guides/batching.md) |
67​
68Not sure which utility you need? Read [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md).
69​
70## Common patterns
71​
72### Control the debouncer directly
73​
74`useDebouncer` returns the instance. Call `maybeExecute` from your event handler, and use `flush` or `cancel` when the user acts before the timer fires.
75​
76```tsx
77import { useState } from 'preact/hooks'
78import { useDebouncer } from '@tanstack/preact-pacer'
79​
80export function DraftEditor() {
81 const [draft, setDraft] = useState('')
82​
83 const saver = useDebouncer(
84 (text: string) => saveDraft(text),
85 { wait: 1000 },
86 (state) => ({ isPending: state.isPending }),
87 )
88​
89 return (
90 <div>
91 <textarea
92 value={draft}
93 onInput={(e) => {
94 setDraft(e.currentTarget.value)
95 saver.maybeExecute(e.currentTarget.value)
96 }}
97 />
98 <button onClick={() => saver.flush()}>Save now</button>
99 <button onClick={() => saver.cancel()}>Discard</button>
100 {saver.state.isPending && <p>Unsaved changes...</p>}
101 </div>
102 )
104```
105​
106### Select the state you render
107​
108The third argument is a selector. Without it, `saver.state` is `{}` and state changes never re-render the component. Select only the fields you render.
109​
110When a child deep in the tree needs the state, use the `Subscribe` component instead. It subscribes that subtree only, so the owning component does not re-render:
111​
112```tsx
113<saver.Subscribe selector={(state) => ({ isPending: state.isPending })}>
114 {({ isPending }) => (isPending ? <span>Saving...</span> : null)}
115</saver.Subscribe>
116```
117​
118Each utility's guide lists the state fields it exposes.
119​
120### Change options between renders
121​
122The hook applies the options you pass on every render, so you can read props and state directly:
123​
124```tsx
125const [debouncedQuery] = useDebouncedValue(query, {
126 wait: isSlowNetwork ? 1000 : 300,
127 enabled: query.length > 2,
128})
129```
130​
131A 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 hook first creates the utility.
132​
133### Run async work
134​
135The async hooks await your function, track execution state, and report errors. This search debounces the request and shows a loading state:
136​
137```tsx
138import { useState } from 'preact/hooks'
139import { useAsyncDebouncer } from '@tanstack/preact-pacer'
140​
141export function AsyncSearch() {
142 const [results, setResults] = useState<Array<SearchResult>>([])
143​
144 const searcher = useAsyncDebouncer(
145 async (term: string) => {
146 const data = await fetchSearchResults(term)
147 setResults(data)
148 return data
149 },
150 {
151 wait: 300,
152 onError: (error) => console.error('Search failed:', error),
153 },
154 (state) => ({ isExecuting: state.isExecuting }),
155 )
156​
157 return (
158 <div>
159 <input onInput={(e) => searcher.maybeExecute(e.currentTarget.value)} />
160 {searcher.state.isExecuting && <p>Loading...</p>}
161 <ul>
162 {results.map((result) => (
163 <li key={result.id}>{result.title}</li>
164 ))}
165 </ul>
166 </div>
167 )
169```
170​
171`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).
172​
173### Limit how often an action runs
174​
175A rate limiter allows a fixed number of calls per window and rejects the rest:
176​
177```tsx
178import { useRateLimiter } from '@tanstack/preact-pacer'
179​
180export function SendButton() {
181 const limiter = useRateLimiter(
182 (message: string) => sendMessage(message),
183 {
184 limit: 5,
185 window: 60_000,
186 onReject: (limiter) =>
187 alert(`Slow down. Try again in ${limiter.getMsUntilNextWindow()} ms.`),
188 },
189 (state) => ({ rejectionCount: state.rejectionCount }),
190 )
191​
192 return (
193 <div>
194 <button onClick={() => limiter.maybeExecute('Hello')}>Send</button>
195 <p>Rejected: {limiter.state.rejectionCount}</p>
196 </div>
197 )
199```
200​
201### Process items in order
202​
203A queuer keeps every item and processes them in order. With `useAsyncQueuer`, `concurrency` sets how many run at once:
204​
205```tsx
206import { useAsyncQueuer } from '@tanstack/preact-pacer'
207​
208export function Uploader() {
209 const queue = useAsyncQueuer(
210 async (file: File) => uploadFile(file),
211 { concurrency: 3 },
212 (state) => ({ size: state.size, activeItems: state.activeItems }),
213 )
214​
215 return (
216 <div>
217 <input
218 type="file"
219 multiple
220 onChange={(e) => {
221 for (const file of e.currentTarget.files ?? []) queue.addItem(file)
222 }}
223 />
224 <p>
225 Uploading {queue.state.activeItems.length}, waiting {queue.state.size}
226 </p>
227 </div>
228 )
230```
231​
232### Callback-only hooks
233​
234When you only need the scheduled function, the callback hooks skip the instance:
235​
236```tsx
237import { useThrottledCallback } from '@tanstack/preact-pacer'
238​
239const onScroll = useThrottledCallback(() => savePosition(window.scrollY), {
240 wait: 200,
241})
242```
243​
244Use the instance hook instead when you need `flush`, `cancel`, or state.
245​
246## Set default options
247​
248`PacerProvider` sets default options for every Pacer hook in its subtree. Options passed to a hook override the defaults.
249​
250```tsx
251import { PacerProvider } from '@tanstack/preact-pacer'
252​
253export function Root() {
254 return (
255 <PacerProvider
256 defaultOptions={{
257 debouncer: { wait: 500 },
258 asyncQueuer: { concurrency: 3 },
259 rateLimiter: { limit: 5, window: 60_000 },
260 }}
261 >
262 <App />
263 </PacerProvider>
264 )
266```
267​
268To share options between specific hooks instead, define them once with an option helper. Helpers such as `debouncerOptions` return the object you pass in, typed for that utility:
269​
270```tsx
271import { debouncerOptions, useDebouncer } from '@tanstack/preact-pacer'
272​
273const searchOptions = debouncerOptions({ wait: 500, leading: false })
274​
275const debouncer = useDebouncer(search, { ...searchOptions, key: 'search' })
276```
277​
278## Control unmount cleanup
279​
280When the component unmounts, 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:
281​
282```tsx
283const saver = useDebouncer(saveDraft, {
284 wait: 1000,
285 onUnmount: (debouncer) => debouncer.flush(),
286})
287```
288​
289## Set up devtools
290​
291Install the devtools packages:
292​
293```sh
294npm install @tanstack/preact-devtools @tanstack/preact-pacer-devtools
295```
296​
297Render the devtools once near the root of your app:
298​
299```tsx
300import { TanStackDevtools } from '@tanstack/preact-devtools'
301import { pacerDevtoolsPlugin } from '@tanstack/preact-pacer-devtools'
302​
303export function App() {
304 return (
305 <>
306 {/* Your app */}
307 <TanStackDevtools plugins={[pacerDevtoolsPlugin()]} />
308 </>
309 )
311```
312​
313A utility appears in the Pacer panel only when you give it a `key` option. See [Devtools](../../devtools.md) for production builds.
314​
315## Next steps
316​
317- [Which Pacer Utility Should I Choose?](../../guides/which-pacer-utility-should-i-choose.md) compares all five utilities.
318- 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.
319- The [Preact API Reference](./reference/index.md) lists every hook and its options.
320- The [Preact examples](./examples/useDebouncer) are runnable apps for each hook.