Open History to see the last commit
1---
2title: Preact Debouncing Guide
3id: debouncing
4---
5
6Debouncing delays a function until calls have stopped for a configured amount of time. Each new call restarts the timer. With the default settings, only the most recent call executes, using its arguments.
7
8Use debouncing when intermediate calls can be discarded and the final value is what matters. Search inputs, form validation, autosave, and resize handling are common examples.
9
10## How debouncing works
11
12The timeline below shows calls arriving in bursts. Every call resets the timer. The final call in each burst executes after three ticks of inactivity.
13
14```text
15Debouncing (wait: 3 ticks)
16Timeline: [1 second per tick]
17Calls: ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️ ⬇️
18Executed: ❌ ❌ ❌ ❌ ❌ ❌ ❌ ❌ ⏳ -> ✅ ❌ ⏳ -> ✅
19 [================================================================]
20 ^ Executes here after
21 3 ticks of no calls
22
23 [Burst of calls] [More calls] [Wait] [New burst]
24 No execution Resets timer Execute Reset and execute
25```
26
27Only the latest call in each burst executes. All earlier calls are discarded.
28
29Debouncing is intentionally lossy. If every operation must run, use [queuing](./queuing.md) instead.
30
31## When to use debouncing
32
33Choose debouncing when:
34
35- You want to wait until activity stops.
36- Only the latest arguments matter.
37- Repeating the operation for every event would waste work.
38- A short delay is acceptable.
39
40Choose another utility when:
41
42- Work should run at a steady interval while activity continues. Use [throttling](./throttling.md).
43- A fixed number of calls may run within a time window. Use [rate limiting](./rate-limiting.md).
44- Every operation must eventually run. Use [queuing](./queuing.md).
45- Several items should be processed together. Use [batching](./batching.md).
46- You need to await a result, handle errors, retry, or abort in-flight work. Use [async debouncing](./async-debouncing.md).
47
48## Choose an API
49
50- `useDebouncedCallback` for a stable debounced event handler
51- `useDebouncedState` or `useDebouncedValue` for delayed Preact state
52- `useDebouncer` for lifecycle methods and selected state
53
54Use the callback API for event handlers, the state or value API for delayed UI state, and the instance API when you need `cancel()`, `flush()`, selected state, or dynamic options.
55
56## Preact example
57
58```tsx
59import { useDebouncedCallback, useDebouncer } from '@tanstack/preact-pacer'
60
61function SearchBox() {
62 const search = useDebouncedCallback(runSearch, { wait: 300 })
63 const debouncer = useDebouncer(saveDraft, { wait: 500 }, (state) => ({
64 isPending: state.isPending,
65 }))
66
67 return (
68 <>
69 <input onChange={(event) => search(event.currentTarget.value)} />
70 <button
71 onClick={() => debouncer.flush()}
72 disabled={!debouncer.state.isPending}
73 >
74 Save now
75 </button>
76 </>
77 )
78}
79```
80
81The focused snippets later in this guide use `useDebouncer` and assume they run inside a component or another hook.
82
83## Execution timing
84
85The `leading` and `trailing` options control which edge of the wait period may execute.
86
87| `leading` | `trailing` | Behavior |
88| --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
89| `false` | `true` | Wait for inactivity, then execute the most recent call. This is the default. |
90| `true` | `false` | Execute the first call immediately. Later calls do not execute and restart the wait period. |
91| `true` | `true` | Execute the first call immediately. If another call arrives during the wait period, execute the most recent call at the trailing edge. |
92| `false` | `false` | Do not execute any calls. |
93
94```ts
95const debouncer = useDebouncer(saveDraft, {
96 wait: 1000,
97 leading: true,
98 trailing: true,
99})
100
101debouncer.maybeExecute('first') // Executes immediately.
102debouncer.maybeExecute('second')
103debouncer.maybeExecute('latest') // Executes after 1 second of inactivity.
104```
105
106With both edges enabled, a single call executes only on the leading edge. A trailing execution occurs only when another call arrives during the wait period.
107
108### No maximum wait
109
110`useDebouncer` does not provide a `maxWait` option. A continuous stream of calls can keep postponing a trailing execution indefinitely. Use [throttling](./throttling.md) when work must continue at a bounded interval while calls are still arriving.
111
112## Controlling pending work
113
114The instance API distinguishes between executing, canceling, and resetting pending work.
115
116### Flush
117
118`flush()` immediately executes the pending trailing call with the most recent arguments. It does nothing when no trailing call is pending.
119
120```ts
121const debouncer = useDebouncer(saveDraft, { wait: 1000 })
122
123debouncer.maybeExecute('draft')
124debouncer.flush() // Executes saveDraft('draft') now.
125```
126
127### Cancel
128
129`cancel()` clears the pending timeout without executing the function. It also allows a leading call to execute immediately the next time `maybeExecute()` is called.
130
131```ts
132debouncer.maybeExecute('discarded draft')
133debouncer.cancel()
134```
135
136### Reset
137
138`reset()` restores the debouncer's state counters and flags to their defaults. It does not clear an already scheduled timeout. Call `cancel()` first when you need to discard pending work and reset state.
139
140```ts
141debouncer.cancel()
142debouncer.reset()
143```
144
145## Configuring behavior at runtime
146
147Use `setOptions()` to change options after construction:
148
149```ts
150debouncer.setOptions({
151 wait: 1000,
152 leading: true,
153 trailing: false,
154})
155```
156
157A new `wait` value applies when the next call schedules a timeout. It does not reschedule a timeout that is already pending. Calling `maybeExecute()` again clears the old timeout and schedules a new one using the current options.
158
159### Enabling and disabling
160
161Set `enabled` to `false` to prevent execution. Disabling a debouncer through `setOptions()` also cancels its pending call.
162
163```ts
164const debouncer = useDebouncer(saveDraft, {
165 wait: 500,
166 enabled: false,
167})
168
169debouncer.maybeExecute('ignored')
170debouncer.setOptions({ enabled: true })
171debouncer.maybeExecute('saved')
172```
173
174The `enabled` and `wait` options may also be functions that receive the debouncer instance:
175
176```ts
177const debouncer = useDebouncer(saveDraft, {
178 enabled: (debouncer) => debouncer.store.state.executionCount < 10,
179 wait: (debouncer) => (debouncer.store.state.executionCount === 0 ? 300 : 500),
180})
181```
182
183### Observing executions
184
185Use `onExecute` for a side effect after the wrapped function runs. The callback receives the executed arguments followed by the debouncer instance.
186
187```ts
188const debouncer = useDebouncer(saveDraft, {
189 wait: 500,
190 onExecute: (args, debouncer) => {
191 console.log('Saved arguments:', args)
192 console.log('Execution count:', debouncer.store.state.executionCount)
193 },
194})
195```
196
197## Preact lifecycle
198
199The adapter cancels pending 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.
200
201## Reactive state
202
203The 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:
204
205```ts
206const debouncer = useDebouncer(saveDraft, { wait: 500 }, (state) => ({
207 isPending: state.isPending,
208 executionCount: state.executionCount,
209}))
210
211console.log(debouncer.state.isPending, debouncer.state.executionCount)
212```
213
214Option 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.
215
216To 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 are not restored.
217
218- `isPending`: Whether a trailing execution is waiting.
219- `executionCount`: How many times the wrapped function has executed.
220- `lastArgs`: The arguments recorded by the most recent trailing-enabled call. Check `isPending` before treating them as pending work.
221- `status`: `'disabled'`, `'idle'`, or `'pending'`.
222
223See the [Preact API reference](../reference/index.md) for adapter signatures and the public core reference for complete option and state types.