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

useAsyncDebouncedCallback.md

70 lines2.1 KB

1---
2id: useAsyncDebouncedCallback
3title: useAsyncDebouncedCallback
4---
5​
6```ts
7function useAsyncDebouncedCallback<TFn>(fn, options): (...args) => Promise<Awaited<ReturnType<TFn>> | undefined>;
8```
9​
10Defined in: [async-debouncer/useAsyncDebouncedCallback.ts:46](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-debouncer/useAsyncDebouncedCallback.ts#L46)
11​
12A React hook that creates a debounced version of an async callback function.
13This hook is a convenient wrapper around the `useAsyncDebouncer` hook,
14providing a stable, debounced async function reference for use in React components.
15​
16The debounced async function will only execute after the specified wait time has elapsed
17since its last invocation. If called again before the wait time expires, the timer
18resets and starts waiting again. The returned function always returns a promise. The call
19that triggers an execution resolves or rejects with that execution's result; superseded
20calls resolve with the most recent result (which may be `undefined` if nothing has executed
21yet), and calls made while the debouncer is disabled resolve with `undefined`.
22​
23This hook provides a simpler API compared to `useAsyncDebouncer`, making it ideal for basic
24async debouncing needs. However, it does not expose the underlying AsyncDebouncer instance.
25​
26For advanced usage requiring features like:
27- Manual cancellation
28- Access to execution/error state
29- Custom useCallback dependencies
30​
31Consider using the `useAsyncDebouncer` hook instead.
32​
33## Type Parameters
34​
35### TFn
36​
37`TFn` *extends* `AnyAsyncFunction`
38​
39## Parameters
40​
41### fn
42​
43`TFn`
44​
45### options
46​
47[`ReactAsyncDebouncerOptions`](../interfaces/ReactAsyncDebouncerOptions.md)\<`TFn`, \{
48\}\>
49​
50## Returns
51​
52(...`args`) => `Promise`\<`Awaited`\<`ReturnType`\<`TFn`\>\> \| `undefined`\>
53​
54## Example
55​
56```tsx
57// Debounce an async search handler
58const handleSearch = useAsyncDebouncedCallback(async (query: string) => {
59 const results = await fetchSearchResults(query);
60 return results;
61}, {
62 wait: 500 // Wait 500ms between executions
63});
64​
65// Use in an input
66<input
67 type="search"
68 onChange={e => handleSearch(e.target.value)}
69/>
70```