Framework
Version
Debouncer API Reference
Throttler API Reference
Rate Limiter API Reference
Queue API Reference
Batcher API Reference

useBatcher

Function: useBatcher()

ts
function useBatcher<TValue>(fn, options): Batcher<TValue>
function useBatcher<TValue>(fn, options): Batcher<TValue>

Defined in: react-pacer/src/batcher/useBatcher.ts:43

A React hook that creates and manages a Batcher instance.

This is a lower-level hook that provides direct access to the Batcher's functionality without any built-in state management. This allows you to integrate it with any state management solution you prefer (useState, Redux, Zustand, etc.) by utilizing the onItemsChange callback.

The Batcher collects items and processes them in batches based on configurable conditions:

  • Maximum batch size
  • Time-based batching (process after X milliseconds)
  • Custom batch processing logic via getShouldExecute

Type Parameters

TValue

Parameters

fn

(items) => void

options

BatcherOptions<TValue> = {}

Returns

Batcher<TValue>

Example

tsx
// Example with custom state management and batching
const [items, setItems] = useState([]);

const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  {
    maxSize: 5,
    wait: 2000,
    onItemsChange: (batcher) => setItems(batcher.peekAllItems()),
    getShouldExecute: (items) => items.length >= 3
  }
);

// Add items to batch - they'll be processed when conditions are met
batcher.addItem(1);
batcher.addItem(2);
batcher.addItem(3); // Triggers batch processing

// Control the batcher
batcher.stop();  // Pause batching
batcher.start(); // Resume batching
// Example with custom state management and batching
const [items, setItems] = useState([]);

const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  {
    maxSize: 5,
    wait: 2000,
    onItemsChange: (batcher) => setItems(batcher.peekAllItems()),
    getShouldExecute: (items) => items.length >= 3
  }
);

// Add items to batch - they'll be processed when conditions are met
batcher.addItem(1);
batcher.addItem(2);
batcher.addItem(3); // Triggers batch processing

// Control the batcher
batcher.stop();  // Pause batching
batcher.start(); // Resume batching
Subscribe to Bytes

Your weekly dose of JavaScript news. Delivered every Monday to over 100,000 devs, for free.

Bytes

No spam. Unsubscribe at any time.