Function Signature
Parameters
() => void
required
A function that performs multiple updates. All state changes within this function will be batched together.
Returns
The function returnsvoid and executes synchronously.
How It Works
When you update multiple stores or atoms, each update normally triggers subscribers immediately. Withbatch(), subscriber notifications are deferred until the batch function completes:
- The batch depth counter is incremented
- Your function executes and makes state changes
- The batch depth counter is decremented
- All queued notifications are flushed at once
Examples
Basic Batching
Optimizing Multiple Updates
Batching with Atoms
Form Updates
Nested Batching
Performance Optimization Example
Conditional Batching
Performance Benefits
Reduced Notifications
Subscribers receive one notification instead of many, reducing callback execution.
Fewer Recomputations
Computed stores/atoms recalculate once instead of for each individual update.
Better UI Performance
In UI frameworks, batching prevents multiple re-renders from cascading updates.
Atomic Updates
All changes appear to happen simultaneously to subscribers, maintaining consistency.
Best Practices
Use batching when:
- Updating multiple related stores/atoms together
- Performing bulk operations
- Updating multiple properties that trigger the same computed values
- Working with forms or complex state objects
Related APIs
- flush - Manually trigger pending notifications
- createStore - Create stores that can be batched
- createAtom - Create atoms that can be batched