📄 tanstack/pacer/latest/docs/framework/react/examples/useBatcher

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

Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/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

React Example: UseBatcher

Github StackBlitz CodeSandbox

=================================================================================================================================================================================================================================================================================================================================================================================================================

Code ExplorerCode

Interactive SandboxSandbox

  • public

  • src

    • index.tsx file iconindex.tsx
  • .eslintrc.cjs file icon.eslintrc.cjs

  • .gitignore file icon.gitignore

  • README.md file iconREADME.md

  • index.html file iconindex.html

  • package.json file iconpackage.json

  • tsconfig.json file icontsconfig.json

  • vite.config.ts file iconvite.config.ts

tsx

import { useState } from 'react'
import ReactDOM from 'react-dom/client'
import { useBatcher } from '@tanstack/react-pacer/batcher'
import { PacerProvider } from '@tanstack/react-pacer/provider'

function App1() {
  // Use your state management library of choice
  const [processedBatches, setProcessedBatches] = useState<
    Array<Array<number>>
  >([])

  // The function that will process a batch of items
  function processBatch(items: Array<number>) {
    setProcessedBatches((prev) => [...prev, items])
    console.log('processing batch', items)
  }

  const batcher = useBatcher(
    processBatch,
    {
      // started: false, // true by default
      maxSize: 5, // Process in batches of 5 (if comes before wait time)
      wait: 3000, // wait up to 3 seconds before processing a batch (if time elapses before maxSize is reached)
      getShouldExecute: (items, _batcher) => items.includes(42), // or pass in a custom function to determine if the batch should be processed
    },
    // Optional Selector function to pick the state you want to track and use
    (state) => ({
      size: state.size,
      executionCount: state.executionCount,
      totalItemsProcessed: state.totalItemsProcessed,
    }),
  )

  return (
    <div>
      <h1>TanStack Pacer useBatcher Example 1</h1>
      <div>Batch Size: {batcher.state.size}</div>
      <div>Batch Max Size: {3}</div>
      <div>Batch Items: {batcher.peekAllItems().join(', ')}</div>
      <div>Batches Processed: {batcher.state.executionCount}</div>
      <div>Items Processed: {batcher.state.totalItemsProcessed}</div>
      <div>
        Processed Batches:{' '}
        {processedBatches.map((b, i) => (
          <>
            <span key={i}>[{b.join(', ')}]</span>,{' '}
          </>
        ))}
      </div>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(2, 1fr)',
          gap: '8px',
          maxWidth: '600px',
          margin: '16px 0',
        }}
      >
        <button
          onClick={() => {
            const nextNumber = batcher.peekAllItems().length
              ? batcher.peekAllItems()[batcher.peekAllItems().length - 1] + 1
              : 1
            batcher.addItem(nextNumber)
          }}
        >
          Add Number
        </button>
        <button
          disabled={batcher.state.size === 0}
          onClick={() => {
            batcher.flush()
          }}
        >
          Flush Current Batch
        </button>
      </div>
      <pre style={{ marginTop: '20px' }}>
        {JSON.stringify(batcher.store.state, null, 2)}
      </pre>
    </div>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root')!)
root.render(
  // optionally, provide default options to an optional PacerProvider
  <PacerProvider
  // defaultOptions={{
  //   batcher: {
  //     maxSize: 10,
  //   },
  // }}
  >
    <div>
      <App1 />
      <hr />
    </div>
  </PacerProvider>,
)


import { useState } from 'react'
import ReactDOM from 'react-dom/client'
import { useBatcher } from '@tanstack/react-pacer/batcher'
import { PacerProvider } from '@tanstack/react-pacer/provider'

function App1() {
  // Use your state management library of choice
  const [processedBatches, setProcessedBatches] = useState<
    Array<Array<number>>
  >([])

  // The function that will process a batch of items
  function processBatch(items: Array<number>) {
    setProcessedBatches((prev) => [...prev, items])
    console.log('processing batch', items)
  }

  const batcher = useBatcher(
    processBatch,
    {
      // started: false, // true by default
      maxSize: 5, // Process in batches of 5 (if comes before wait time)
      wait: 3000, // wait up to 3 seconds before processing a batch (if time elapses before maxSize is reached)
      getShouldExecute: (items, _batcher) => items.includes(42), // or pass in a custom function to determine if the batch should be processed
    },
    // Optional Selector function to pick the state you want to track and use
    (state) => ({
      size: state.size,
      executionCount: state.executionCount,
      totalItemsProcessed: state.totalItemsProcessed,
    }),
  )

  return (
    <div>
      <h1>TanStack Pacer useBatcher Example 1</h1>
      <div>Batch Size: {batcher.state.size}</div>
      <div>Batch Max Size: {3}</div>
      <div>Batch Items: {batcher.peekAllItems().join(', ')}</div>
      <div>Batches Processed: {batcher.state.executionCount}</div>
      <div>Items Processed: {batcher.state.totalItemsProcessed}</div>
      <div>
        Processed Batches:{' '}
        {processedBatches.map((b, i) => (
          <>
            <span key={i}>[{b.join(', ')}]</span>,{' '}
          </>
        ))}
      </div>
      <div
        style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(2, 1fr)',
          gap: '8px',
          maxWidth: '600px',
          margin: '16px 0',
        }}
      >
        <button
          onClick={() => {
            const nextNumber = batcher.peekAllItems().length
              ? batcher.peekAllItems()[batcher.peekAllItems().length - 1] + 1
              : 1
            batcher.addItem(nextNumber)
          }}
        >
          Add Number
        </button>
        <button
          disabled={batcher.state.size === 0}
          onClick={() => {
            batcher.flush()
          }}
        >
          Flush Current Batch
        </button>
      </div>
      <pre style={{ marginTop: '20px' }}>
        {JSON.stringify(batcher.store.state, null, 2)}
      </pre>
    </div>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root')!)
root.render(
  // optionally, provide default options to an optional PacerProvider
  <PacerProvider
  // defaultOptions={{
  //   batcher: {
  //     maxSize: 10,
  //   },
  // }}
  >
    <div>
      <App1 />
      <hr />
    </div>
  </PacerProvider>,
)

asyncBatch

useAsyncBatcher

Partners Become a Partner

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

scarf analytics