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

useAsyncBatchedCallback.md

68 lines1.9 KB

1---
2id: useAsyncBatchedCallback
3title: useAsyncBatchedCallback
4---
5​
6```ts
7function useAsyncBatchedCallback<TValue>(fn, options): (item) => Promise<void>;
8```
9​
10Defined in: [async-batcher/useAsyncBatchedCallback.ts:42](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/async-batcher/useAsyncBatchedCallback.ts#L42)
11​
12A React hook that creates a batched version of an async callback function.
13This hook is a convenient wrapper around the `useAsyncBatcher` hook,
14providing a stable, batched async function reference for use in React components.
15​
16The batched async function will collect individual calls into batches and execute them
17when batch conditions are met (max size reached, wait time elapsed, or custom logic).
18The returned function always returns a promise that resolves with undefined (since the
19batch function processes multiple items together).
20​
21This hook provides a simpler API compared to `useAsyncBatcher`, making it ideal for basic
22async batching needs. However, it does not expose the underlying AsyncBatcher instance.
23​
24For advanced usage requiring features like:
25- Manual batch execution
26- Access to batch results and state
27- Custom useCallback dependencies
28​
29Consider using the `useAsyncBatcher` hook instead.
30​
31## Type Parameters
32​
33### TValue
34​
35`TValue`
36​
37## Parameters
38​
39### fn
40​
41(`items`) => `Promise`\<`unknown`\>
42​
43### options
44​
45[`ReactAsyncBatcherOptions`](../interfaces/ReactAsyncBatcherOptions.md)\<`TValue`, \{
46\}\>
47​
48## Returns
49​
50(`item`) => `Promise`\<`void`\>
51​
52## Example
53​
54```tsx
55// Batch API requests
56const batchApiCall = useAsyncBatchedCallback(async (requests: ApiRequest[]) => {
57 const results = await Promise.all(requests.map(req => fetch(req.url)));
58 return results.map(res => res.json());
59}, {
60 maxSize: 10, // Process when 10 requests collected
61 wait: 1000 // Or after 1 second
62});
63​
64// Use in event handlers
65<button onClick={() => batchApiCall({ url: '/api/analytics', data: eventData })}>
66 Track Event
67</button>
68```