Skip to main content

Function Signature

Batches multiple store or atom updates into a single update cycle. This prevents unnecessary re-renders and notifications by deferring subscriber notifications until all updates within the batch are complete.

Parameters

() => void
required
A function that performs multiple updates. All state changes within this function will be batched together.

Returns

The function returns void and executes synchronously.

How It Works

When you update multiple stores or atoms, each update normally triggers subscribers immediately. With batch(), subscriber notifications are deferred until the batch function completes:
  1. The batch depth counter is incremented
  2. Your function executes and makes state changes
  3. The batch depth counter is decremented
  4. All queued notifications are flushed at once
This ensures that subscribers only receive one notification for all the batched changes, rather than one per change.

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
Avoid batching when:
  • Only updating a single store
  • You need intermediate states to be observable
  • The operations are naturally separated in time
  • Debugging state changes (batching can hide the update sequence)
  • flush - Manually trigger pending notifications
  • createStore - Create stores that can be batched
  • createAtom - Create atoms that can be batched