📄 tanstack/pacer/latest/docs/framework/react/reference/functions/useBatcher

File: useBatcher.md | Updated: 11/15/2025

Source: https://tanstack.com/pacer/latest/docs/framework/react/reference/functions/useBatcher



TanStack

Pacer v0v0

Search...

+ K

Auto

Log In

TanStack StartRC

Docs Examples GitHub Contributors

TanStack Router

Docs Examples GitHub Contributors

TanStack Query

Docs Examples GitHub Contributors

TanStack Table

Docs Examples Github Contributors

TanStack Formnew

Docs Examples Github Contributors

TanStack DBbeta

Docs Github Contributors

TanStack Virtual

Docs Examples Github Contributors

TanStack Paceralpha

Docs Examples Github Contributors

TanStack Storealpha

Docs Examples Github Contributors

TanStack Devtoolsalpha

Docs Github Contributors

More Libraries

Maintainers Partners Support Learn StatsBETA Discord Merch Blog GitHub Ethos Brand Guide

Documentation

Framework

React logo

React

Version

Latest

Search...

+ K

Menu

Getting Started

Guides

API Reference

Debouncer API Reference

Throttler API Reference

Rate Limiter API Reference

Queue API Reference

Batcher API Reference

Debouncer Examples

Throttler Examples

Rate Limiter Examples

Queue Examples

Batcher Examples

TanStack Query Examples

Framework

React logo

React

Version

Latest

Menu

Getting Started

Guides

API Reference

Debouncer API Reference

Throttler API Reference

Rate Limiter API Reference

Queue API Reference

Batcher API Reference

Debouncer Examples

Throttler Examples

Rate Limiter Examples

Queue Examples

Batcher Examples

TanStack Query Examples

On this page

useBatcher

Copy Markdown

Function: useBatcher()
======================

ts

function useBatcher<TValue, TSelected>(
   fn, 
   options, 
selector): ReactBatcher<TValue, TSelected>;


function useBatcher<TValue, TSelected>(
   fn, 
   options, 
selector): ReactBatcher<TValue, TSelected>;

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

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

State Management and Selector
-----------------------------

The hook uses TanStack Store for reactive state management. The selector parameter allows you to specify which state changes will trigger a re-render, optimizing performance by preventing unnecessary re-renders when irrelevant state changes occur.

By default, there will be no reactive state subscriptions and you must opt-in to state tracking by providing a selector function. This prevents unnecessary re-renders and gives you full control over when your component updates. Only when you provide a selector will the component re-render when the selected state values change.

Available state properties:

  • executionCount: Number of batch executions that have been completed
  • isEmpty: Whether the batcher has no items to process
  • isPending: Whether the batcher is waiting for the timeout to trigger batch processing
  • isRunning: Whether the batcher is active and will process items automatically
  • items: Array of items currently queued for batch processing
  • size: Number of items currently in the batch queue
  • status: Current processing status ('idle' | 'pending')
  • totalItemsProcessed: Total number of items processed across all batches

Type Parameters
---------------
### TValue

TValue

### TSelected

TSelected = { }

Parameters
----------
### fn

(items) => void

### options

BatcherOptions<TValue> = {}

### selector

(state) => TSelected

Returns
-------

ReactBatcher <TValue, TSelected>

Example
-------

tsx

// Default behavior - no reactive state subscriptions
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 }
);

// Opt-in to re-render when batch size changes (optimized for displaying queue size)
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 },
  (state) => ({
    size: state.size,
    isEmpty: state.isEmpty
  })
);

// Opt-in to re-render when execution metrics change (optimized for stats display)
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 },
  (state) => ({
    executionCount: state.executionCount,
    totalItemsProcessed: state.totalItemsProcessed
  })
);

// Opt-in to re-render when processing state changes (optimized for loading indicators)
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 },
  (state) => ({
    isPending: state.isPending,
    isRunning: state.isRunning,
    status: state.status
  })
);

// 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

// Access the selected state (will be empty object {} unless selector provided)
const { size, isPending } = batcher.state;


// Default behavior - no reactive state subscriptions
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 }
);

// Opt-in to re-render when batch size changes (optimized for displaying queue size)
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 },
  (state) => ({
    size: state.size,
    isEmpty: state.isEmpty
  })
);

// Opt-in to re-render when execution metrics change (optimized for stats display)
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 },
  (state) => ({
    executionCount: state.executionCount,
    totalItemsProcessed: state.totalItemsProcessed
  })
);

// Opt-in to re-render when processing state changes (optimized for loading indicators)
const batcher = useBatcher<number>(
  (items) => console.log('Processing batch:', items),
  { maxSize: 5, wait: 2000 },
  (state) => ({
    isPending: state.isPending,
    isRunning: state.isRunning,
    status: state.status
  })
);

// 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

// Access the selected state (will be empty object {} unless selector provided)
const { size, isPending } = batcher.state;

Edit on GitHub

ReactAsyncBatcher

useAsyncBatcher

Partners Become a Partner

Code RabbitCode Rabbit CloudflareCloudflare AG GridAG Grid NetlifyNetlify NeonNeon WorkOSWorkOS ClerkClerk ConvexConvex ElectricElectric SentrySentry PrismaPrisma StrapiStrapi UnkeyUnkey

scarf analytics