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

useAsyncDebouncer.md

197 lines6.8 KB

1---
2id: useAsyncDebouncer
3title: useAsyncDebouncer
4---
5​
6```ts
7function useAsyncDebouncer<TFn, TSelected>(
8 fn,
9 options,
10selector?): PreactAsyncDebouncer<TFn, TSelected>;
11```
12​
13Defined in: [async-debouncer/useAsyncDebouncer.ts:214](https://github.com/TanStack/pacer/blob/main/packages/preact-pacer/src/async-debouncer/useAsyncDebouncer.ts#L214)
14​
15A low-level Preact hook that creates an `AsyncDebouncer` instance to delay execution of an async function.
16​
17This hook is designed to be flexible and state-management agnostic - it simply returns a debouncer instance that
18you can integrate with any state management solution (useState, Redux, Zustand, Jotai, etc).
19​
20Async debouncing ensures that an async function only executes after a specified delay has passed since its last invocation.
21Each new invocation resets the delay timer. This is useful for handling frequent events like window resizing
22or input changes where you only want to execute the handler after the events have stopped occurring.
23​
24Unlike throttling which allows execution at regular intervals, debouncing prevents any execution until
25the function stops being called for the specified delay period.
26​
27Unlike the non-async Debouncer, this async version supports returning values from the debounced function,
28making it ideal for API calls and other async operations where you want the result of the `maybeExecute` call
29instead of setting the result on a state variable from within the debounced function.
30​
31Error Handling:
32- If an `onError` handler is provided, it will be called with the error and debouncer instance
33- If `throwOnError` is true (default when no onError handler is provided), the error will be thrown
34- If `throwOnError` is false (default when onError handler is provided), the error will be swallowed
35- Both onError and throwOnError can be used together - the handler will be called before any error is thrown
36- The error state can be checked using the underlying AsyncDebouncer instance
37​
38## State Management and Selector
39​
40The hook uses TanStack Store for reactive state management. You can subscribe to state changes
41in two ways:
42​
43**1. Using `debouncer.Subscribe` HOC (Recommended for component tree subscriptions)**
44​
45Use the `Subscribe` HOC to subscribe to state changes deep in your component tree without
46needing to pass a selector to the hook. This is ideal when you want to subscribe to state
47in child components.
48​
49**2. Using the `selector` parameter (For hook-level subscriptions)**
50​
51The `selector` parameter allows you to specify which state changes will trigger a re-render
52at the hook level, optimizing performance by preventing unnecessary re-renders when irrelevant
53state changes occur.
54​
55**By default, there will be no reactive state subscriptions** and you must opt-in to state
56tracking by providing a selector function or using the `Subscribe` HOC. This prevents unnecessary
57re-renders and gives you full control over when your component updates.
58​
59Available state properties:
60- `canLeadingExecute`: Whether the debouncer can execute on the leading edge
61- `errorCount`: Number of function executions that have resulted in errors
62- `isExecuting`: Whether the debounced function is currently executing asynchronously
63- `isPending`: Whether the debouncer is waiting for the timeout to trigger execution
64- `lastArgs`: The arguments from the most recent call to maybeExecute
65- `lastResult`: The result from the most recent successful function execution
66- `settleCount`: Number of function executions that have completed (success or error)
67- `status`: Current execution status ('disabled' | 'idle' | 'pending' | 'executing' | 'settled')
68- `successCount`: Number of function executions that have completed successfully
69​
70## Unmount behavior
71​
72By default, the hook cancels any pending execution and aborts any in-flight execution when the component unmounts.
73Abort only cancels underlying operations (e.g. fetch) when the abort signal from `getAbortSignal()` is passed to them.
74Use the `onUnmount` option to customize this. For example, to flush pending work instead:
75​
76```tsx
77const debouncer = useAsyncDebouncer(fn, {
78 wait: 500,
79 onUnmount: (d) => d.flush()
80});
81```
82​
83Note: For async utils, `flush()` returns a Promise and runs fire-and-forget in the cleanup.
84If your debounced function updates Preact state, those updates may run after the component has
85unmounted, which can cause "setState on unmounted component" warnings. Guard your callbacks
86accordingly when using onUnmount with flush.
87​
88## Type Parameters
89​
90### TFn
91​
92`TFn` *extends* `AnyAsyncFunction`
93​
94### TSelected
95​
96`TSelected` = \{
97\}
98​
99## Parameters
100​
101### fn
102​
103`TFn`
104​
105### options
106​
107[`PreactAsyncDebouncerOptions`](../interfaces/PreactAsyncDebouncerOptions.md)\<`TFn`, `TSelected`\>
108​
109### selector?
110​
111(`state`) => `TSelected`
112​
113## Returns
114​
115[`PreactAsyncDebouncer`](../interfaces/PreactAsyncDebouncer.md)\<`TFn`, `TSelected`\>
116​
117## Example
118​
119```tsx
120// Default behavior - no reactive state subscriptions
121const searchDebouncer = useAsyncDebouncer(
122 async (query: string) => {
123 const results = await api.search(query);
124 return results;
125 },
126 { wait: 500 }
127);
128​
129// Subscribe to state changes deep in component tree using Subscribe HOC
130<searchDebouncer.Subscribe selector={(state) => ({ isPending: state.isPending })}>
131 {({ isPending }) => (
132 <div>{isPending ? 'Searching...' : 'Ready'}</div>
133 )}
134</searchDebouncer.Subscribe>
135​
136// Opt-in to re-render when execution state changes at hook level (optimized for loading indicators)
137const searchDebouncer = useAsyncDebouncer(
138 async (query: string) => {
139 const results = await api.search(query);
140 return results;
141 },
142 { wait: 500 },
143 (state) => ({
144 isExecuting: state.isExecuting,
145 isPending: state.isPending
146 })
147);
148​
149// Opt-in to re-render when results are available (optimized for data display)
150const searchDebouncer = useAsyncDebouncer(
151 async (query: string) => {
152 const results = await api.search(query);
153 return results;
154 },
155 { wait: 500 },
156 (state) => ({
157 lastResult: state.lastResult,
158 successCount: state.successCount
159 })
160);
161​
162// Opt-in to re-render when error state changes (optimized for error handling)
163const searchDebouncer = useAsyncDebouncer(
164 async (query: string) => {
165 const results = await api.search(query);
166 return results;
167 },
168 {
169 wait: 500,
170 onError: (error) => console.error('Search failed:', error)
171 },
172 (state) => ({
173 errorCount: state.errorCount,
174 status: state.status
175 })
176);
177​
178// With state management
179const [results, setResults] = useState([]);
180const { maybeExecute, state } = useAsyncDebouncer(
181 async (searchTerm) => {
182 const data = await searchAPI(searchTerm);
183 setResults(data);
184 },
185 {
186 wait: 300,
187 leading: true, // Execute immediately on first call
188 trailing: false, // Skip trailing edge updates
189 onError: (error) => {
190 console.error('API call failed:', error);
191 }
192 }
193);
194​
195// Access the selected state (will be empty object {} unless selector provided)
196const { isExecuting, lastResult } = state;
197```