Skip to main content

What is Batching?

Batching is a performance optimization technique that allows you to group multiple state updates together so that subscribers are only notified once, after all updates are complete. This is especially useful when you need to update multiple stores or make several updates to the same store in quick succession. Without batching, each update would trigger all subscribers immediately, potentially causing unnecessary re-renders, computations, or side effects.

The Problem Batching Solves

Consider this scenario without batching:
With batching, you can make both updates trigger only one notification:

Using the batch Function

Basic Usage

API Signature

The batch function takes a callback that performs multiple updates. All subscriptions are deferred until the callback completes.

How Batching Works

From batch.ts:4-12:
  1. Start Batch: Increments an internal batch depth counter
  2. Execute Updates: Runs your callback with all the updates
  3. End Batch: Decrements the batch depth counter
  4. Flush: If batch depth is 0, notifies all subscribers that were queued during the batch
Batching uses a depth counter, so nested batch() calls work correctly. Notifications only fire when the outermost batch completes.

Practical Examples

Form Updates

Multiple Store Updates

Bulk Operations

Animation Frame Updates

Data Sync

Undo/Redo

Nested Batching

Batching supports nesting. Notifications only fire when the outermost batch completes:

Performance Considerations

When to Use Batching

  • Multiple related updates
  • Bulk operations
  • Animation loops
  • Data synchronization
  • Form initialization

When Not to Use Batching

  • Single updates
  • When you need immediate feedback
  • Unrelated updates
  • Simple derived state

Measuring Impact

Best Practices

Before batching multiple setState calls, consider if you can do it in one update:
Batching has a small overhead. Don’t batch single updates:
The batch function uses try/finally to ensure cleanup. Errors will propagate:

Stores

Learn about the store primitive

Atoms

Lower-level reactive primitives

Subscriptions

Understand how batching affects subscriptions

Derived Stores

See how batching optimizes derived computations