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

useBatchedCallback.md

66 lines1.6 KB

1---
2id: useBatchedCallback
3title: useBatchedCallback
4---
5​
6```ts
7function useBatchedCallback<TValue>(fn, options): (item) => void;
8```
9​
10Defined in: [batcher/useBatchedCallback.ts:40](https://github.com/TanStack/pacer/blob/main/packages/react-pacer/src/batcher/useBatchedCallback.ts#L40)
11​
12A React hook that creates a batched version of a callback function.
13This hook is essentially a wrapper around the basic `batch` function
14that is exported from `@tanstack/pacer`,
15but optimized for React with reactive options and a stable function reference.
16​
17The batched function will collect individual calls into batches and execute them
18when batch conditions are met (max size reached, wait time elapsed, or custom logic).
19​
20This hook provides a simpler API compared to `useBatcher`, making it ideal for basic
21batching needs. However, it does not expose the underlying Batcher instance.
22​
23For advanced usage requiring features like:
24- Manual batch execution
25- Access to batch state and metrics
26- Custom useCallback dependencies
27​
28Consider using the `useBatcher` hook instead.
29​
30## Type Parameters
31​
32### TValue
33​
34`TValue`
35​
36## Parameters
37​
38### fn
39​
40(`items`) => `void`
41​
42### options
43​
44[`ReactBatcherOptions`](../interfaces/ReactBatcherOptions.md)\<`TValue`, \{
45\}\>
46​
47## Returns
48​
49(`item`) => `void`
50​
51## Example
52​
53```tsx
54// Batch analytics events
55const trackEvents = useBatchedCallback((events: AnalyticsEvent[]) => {
56 sendAnalytics(events);
57}, {
58 maxSize: 5, // Process when 5 events collected
59 wait: 2000 // Or after 2 seconds
60});
61​
62// Use in event handlers
63<button onClick={() => trackEvents({ type: 'click', target: 'button' })}>
64 Click me
65</button>
66```