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

async-debouncing.md

179 lines7.6 KB

1---
2title: React Async Debouncing Guide
3id: async-debouncing
4---
5​
6Async debouncing keeps the timing behavior described in the [Debouncing Guide](./debouncing.md), while adding Promise results, retries, error callbacks, and control over in-flight work.
7​
8Use async debouncing when the debounced operation returns a value you need, can reject, or needs retry and abort support. The synchronous debouncing adapter can call an async function as a side effect, but it does not manage the resulting Promise.
9​
10## Choose an API
11​
12- `useAsyncDebouncedCallback` for a stable Promise-returning handler
13- `useAsyncDebouncer` for lifecycle methods and selected execution state
14​
15## React example
16​
17```tsx
18import { useAsyncDebouncedCallback } from '@tanstack/react-pacer'
19​
20function SearchBox() {
21 const search = useAsyncDebouncedCallback(fetchSearchResults, {
22 wait: 300,
23 onError: reportError,
24 })
25​
26 return <input onChange={(event) => void search(event.currentTarget.value)} />
28```
29​
30The focused snippets later in this guide use `useAsyncDebouncer` and assume they run inside a component or another hook.
31​
32## Promise results
33​
34`maybeExecute()` returns a Promise. A call that owns an execution resolves with that execution's result. There is one important consequence when a pending trailing call is replaced:
35​
36```text
37call A ──────┐
38 ├─ call B replaces A ───── wait ───── execute B
39Promise A ───┘ resolves with the previous lastResult
40Promise B ─────────────────────────────── resolves with result B
41```
42​
43The replaced call resolves immediately with the debouncer's current `lastResult`, which is often `undefined` before the first successful execution. It does not wait for the newer call. Treat the Promise returned by the latest call as the owner of the pending result.
44​
45If you need every invocation to execute and produce its own result, use an [Async Queue](./async-queuing.md) instead.
46​
47## Leading and trailing execution
48​
49The four combinations match synchronous debouncing:
50​
51| `leading` | `trailing` | Behavior |
52| --------- | ---------- | ---------------------------------------------------------------------------------- |
53| `false` | `true` | Execute after calls stop for `wait` milliseconds. This is the default. |
54| `true` | `false` | Execute immediately, then ignore calls until the quiet period ends. |
55| `true` | `true` | Execute the first call immediately and the latest later call on the trailing edge. |
56| `false` | `false` | Record calls without executing the function. |
57​
58With both edges enabled, a single call executes only on the leading edge. A trailing execution requires another call during the wait period.
59​
60## Errors and callbacks
61​
62Async debouncers provide callbacks around each actual execution:
63​
64- `onSuccess(result, args, debouncer)` runs after a successful execution.
65- `onError(error, args, debouncer)` runs after the retries for an execution fail.
66- `onSettled(args, debouncer)` runs after either outcome.
67​
68Without `onError`, `throwOnError` defaults to `true`, so an execution failure rejects the Promise. Providing `onError` changes that default to `false`; the Promise then resolves with the current `lastResult`. Set `throwOnError` explicitly when you want different behavior.
69​
70Callbacks run for executions, not for every call to `maybeExecute()`. Replaced or canceled pending calls never reach the wrapped function.
71​
72## Retrying failed executions
73​
74Pass `asyncRetryerOptions` to retry an execution after it starts:
75​
76```ts
77const save = useAsyncDebouncer(saveDraft, {
78 wait: 500,
79 asyncRetryerOptions: {
80 maxAttempts: 3,
81 backoff: 'exponential',
82 baseWait: 500,
83 jitter: 0.2,
84 },
85})
86```
87​
88`maxAttempts` includes the first attempt. Debouncing decides when one logical execution starts; the retryer then manages attempts for that execution. See the [Async Retrying Guide](./async-retrying.md) for retry safety, backoff, and timeout behavior.
89​
90## Canceling pending work and aborting active work
91​
92Pending and active work have separate controls:
93​
94- `cancel()` clears a trailing execution that has not started. It does not stop an active Promise.
95- `abort()` aborts active executions. It does not clear a pending trailing execution.
96- `flush()` starts pending work immediately and returns its result. It does not affect active work.
97​
98For an underlying operation such as `fetch` to stop, pass the debouncer's signal to it:
99​
100```ts
101const search = useAsyncDebouncer(
102 async (query: string) => {
103 const response = await fetch(`/api/search?q=${query}`, {
104 signal: search.getAbortSignal() ?? undefined,
105 })
106 return response.json()
107 },
108 { wait: 300 },
110​
111search.maybeExecute('pacer')
112search.abort()
113```
114​
115Calling `abort()` without using the signal stops retry management but cannot force an arbitrary Promise to stop.
116​
117### Resetting safely
118​
119`reset()` restores default state, but it does not clear a scheduled trailing timeout or guarantee that active work stops. Use the lifecycle methods first when you need a complete cleanup:
120​
121```ts
122search.cancel()
123search.abort()
124search.reset()
125```
126​
127## Configuration
128​
129`wait` and `enabled` may be values or functions that receive the debouncer instance. `setOptions()` merges new options into the current configuration.
130​
131```ts
132search.setOptions({
133 enabled: (debouncer) => debouncer.store.state.errorCount < 3,
134 wait: (debouncer) => (debouncer.store.state.successCount === 0 ? 200 : 500),
135})
136```
137​
138Changing `wait` does not reschedule an existing timeout. The new value applies when later work is scheduled.
139​
140Use `asyncDebouncerOptions()` to define reusable, type-checked option objects.
141​
142## React lifecycle
143​
144The adapter cancels pending work and aborts active work when its owner is destroyed. Providing `onUnmount` replaces that default cleanup, so a custom callback must perform every required lifecycle action. When custom cleanup flushes work, remember that user callbacks can run while the component is being destroyed.
145​
146## Reactive state
147​
148The adapter subscribes only to the state returned by the selector argument. Without a selector, the adapter state is empty. Create the utility at the top level of a component or another hook and select only fields used by the view:
149​
150```ts
151const debouncer = useAsyncDebouncer(
152 fetchSearchResults,
153 { wait: 300 },
154 (state) => ({
155 isPending: state.isPending,
156 isExecuting: state.isExecuting,
157 lastResult: state.lastResult,
158 }),
160​
161console.log(
162 debouncer.state.isPending,
163 debouncer.state.isExecuting,
164 debouncer.state.lastResult,
166```
167​
168Option functions and lifecycle callbacks receive the underlying public utility instance. The `.store.state` reads inside those callbacks in the examples above are supported. Rendering code should read the selected adapter state shown here.
169​
170To restore selected state that your app has persisted, pass a partial snapshot through `initialState`. It is merged with the defaults. Restore only durable fields. Pending timers and active executions are not restored.
171​
172- `isPending`: Whether a trailing execution is scheduled.
173- `isExecuting`: Whether the wrapped function is active.
174- `lastArgs`: The arguments retained for pending work.
175- `lastResult`: The most recent successful result.
176- `successCount`, `errorCount`, and `settleCount`: Execution outcome counts.
177- `status`: `'disabled'`, `'idle'`, `'pending'`, `'executing'`, or `'settled'`.
178​
179See the [React API reference](../reference/index.md) for adapter signatures and the public core reference for complete option and state types.