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

debouncing.md

259 lines9.8 KB

1---
2title: React 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## Using debouncing in React
49​
50The React adapter provides three levels of debouncing API:
51​
52- `useDebouncedCallback` creates a stable debounced event handler.
53- `useDebouncedState` and `useDebouncedValue` delay state or a changing value.
54- `useDebouncer` exposes lifecycle methods, dynamic options, callbacks, and selected state.
55​
56Call these hooks at the top level of a component or another hook. The focused examples later in this guide assume they run in that context.
57​
58### Debounced callback
59​
60Use `useDebouncedCallback` when an event should invoke a debounced side effect:
61​
62```tsx
63import { useDebouncedCallback } from '@tanstack/react-pacer'
64​
65function SearchBox() {
66 const search = useDebouncedCallback(
67 (query: string) => updateSearchResults(query),
68 { wait: 500 },
69 )
70​
71 return (
72 <input
73 onChange={(event) => search(event.currentTarget.value)}
74 placeholder="Search"
75 />
76 )
78```
79​
80The callback does not expose `cancel()` or `flush()`. Use `useDebouncer` when the component needs that control.
81​
82### Debounced state and values
83​
84Use `useDebouncedState` when Pacer should own the delayed state, or `useDebouncedValue` when a value already changes elsewhere:
85​
86```tsx
87import { useDebouncedValue } from '@tanstack/react-pacer'
88​
89function Results({ query }: { query: string }) {
90 const [debouncedQuery] = useDebouncedValue(query, { wait: 500 })
91​
92 return <SearchResults query={debouncedQuery} />
94```
95​
96### Instance API
97​
98```tsx
99import { useDebouncer } from '@tanstack/react-pacer'
100​
101function SaveControls() {
102 const debouncer = useDebouncer(saveDraft, { wait: 500 }, (state) => ({
103 isPending: state.isPending,
104 }))
105​
106 return (
107 <button
108 disabled={!debouncer.state.isPending}
109 onClick={() => debouncer.flush()}
110 >
111 Save now
112 </button>
113 )
115```
116​
117Both the callback and `maybeExecute()` return `void`. The synchronous adapter does not retain return values or catch errors. Handle errors inside a trailing callback, or use [async debouncing](./async-debouncing.md) when the caller needs a Promise result.
118​
119## Execution timing
120​
121The `leading` and `trailing` options control which edge of the wait period may execute.
122​
123| `leading` | `trailing` | Behavior |
124| --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------- |
125| `false` | `true` | Wait for inactivity, then execute the most recent call. This is the default. |
126| `true` | `false` | Execute the first call immediately. Later calls do not execute and restart the wait period. |
127| `true` | `true` | Execute the first call immediately. If another call arrives during the wait period, execute the most recent call at the trailing edge. |
128| `false` | `false` | Do not execute any calls. |
129​
130```ts
131const debouncer = useDebouncer(saveDraft, {
132 wait: 1000,
133 leading: true,
134 trailing: true,
135})
136​
137debouncer.maybeExecute('first') // Executes immediately.
138debouncer.maybeExecute('second')
139debouncer.maybeExecute('latest') // Executes after 1 second of inactivity.
140```
141​
142With 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.
143​
144### No maximum wait
145​
146`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.
147​
148## Controlling pending work
149​
150The instance API distinguishes between executing, canceling, and resetting pending work.
151​
152### Flush
153​
154`flush()` immediately executes the pending trailing call with the most recent arguments. It does nothing when no trailing call is pending.
155​
156```ts
157const debouncer = useDebouncer(saveDraft, { wait: 1000 })
158​
159debouncer.maybeExecute('draft')
160debouncer.flush() // Executes saveDraft('draft') now.
161```
162​
163### Cancel
164​
165`cancel()` clears the pending timeout without executing the function. It also allows a leading call to execute immediately the next time `maybeExecute()` is called.
166​
167```ts
168debouncer.maybeExecute('discarded draft')
169debouncer.cancel()
170```
171​
172### Reset
173​
174`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.
175​
176```ts
177debouncer.cancel()
178debouncer.reset()
179```
180​
181## Configuring behavior at runtime
182​
183Use `setOptions()` to change options after construction:
184​
185```ts
186debouncer.setOptions({
187 wait: 1000,
188 leading: true,
189 trailing: false,
190})
191```
192​
193A 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.
194​
195### Enabling and disabling
196​
197Set `enabled` to `false` to prevent execution. Disabling a debouncer through `setOptions()` also cancels its pending call.
198​
199```ts
200const debouncer = useDebouncer(saveDraft, {
201 wait: 500,
202 enabled: false,
203})
204​
205debouncer.maybeExecute('ignored')
206debouncer.setOptions({ enabled: true })
207debouncer.maybeExecute('saved')
208```
209​
210The `enabled` and `wait` options may also be functions that receive the debouncer instance:
211​
212```ts
213const debouncer = useDebouncer(saveDraft, {
214 enabled: (debouncer) => debouncer.store.state.executionCount < 10,
215 wait: (debouncer) => (debouncer.store.state.executionCount === 0 ? 300 : 500),
216})
217```
218​
219### Observing executions
220​
221Use `onExecute` for a side effect after the wrapped function runs. The callback receives the executed arguments followed by the debouncer instance.
222​
223```ts
224const debouncer = useDebouncer(saveDraft, {
225 wait: 500,
226 onExecute: (args, debouncer) => {
227 console.log('Saved arguments:', args)
228 console.log('Execution count:', debouncer.store.state.executionCount)
229 },
230})
231```
232​
233## React lifecycle
234​
235The adapter cancels pending work when the component unmounts. Providing `onUnmount` replaces that default cleanup, so a custom callback must perform every required lifecycle action. This matters most when flushing during unmount because callbacks may run after the component has begun tearing down.
236​
237## Reactive state
238​
239The adapter exposes reactive state only through the selector passed as the third argument. Without a selector, `debouncer.state` is an empty object. Select only fields used by the component:
240​
241```tsx
242const debouncer = useDebouncer(fn, options, (state) => ({
243 isPending: state.isPending,
244 executionCount: state.executionCount,
245}))
246​
247console.log(debouncer.state.isPending, debouncer.state.executionCount)
248```
249​
250Option functions and lifecycle callbacks receive the underlying public utility instance. The `.store.state` reads inside those callbacks in the examples above are supported. Component rendering should use selected adapter state.
251​
252To 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.
253​
254- `isPending`: Whether a trailing execution is waiting.
255- `executionCount`: How many times the wrapped function has executed.
256- `lastArgs`: The arguments recorded by the most recent trailing-enabled call. Check `isPending` before treating them as pending work.
257- `status`: `'disabled'`, `'idle'`, or `'pending'`.
258​
259See the [React API reference](../reference/index.md) for adapter signatures and the public core reference for complete option and state types.