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:Using the batch Function
Basic Usage
API Signature
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:- Start Batch: Increments an internal batch depth counter
- Execute Updates: Runs your callback with all the updates
- End Batch: Decrements the batch depth counter
- 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
Consider Single Updates First
Consider Single Updates First
Before batching multiple
setState calls, consider if you can do it in one update:Don't Over-Batch
Don't Over-Batch
Batching has a small overhead. Don’t batch single updates:
Handle Errors Properly
Handle Errors Properly
The
batch function uses try/finally to ensure cleanup. Errors will propagate:Related Concepts
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