createBatch

Executes a function in a batch, ensuring that all signal updates within the function only trigger effects once at the end, instead of immediately after each update.

Signature

function createBatch(fn: () => void): void;

Parameters

  • fn: () => void - The function to execute within the batch context

Example

const [x, setX] = createSignal(0);
const [y, setY] = createSignal(0);

createEffect(() => {
  console.log("Sum:", x() + y());
});

// Without batching, the effect triggers twice
setX(1); // Log: Sum: 1
setY(2); // Log: Sum: 3

// With batching, it triggers only once
createBatch(() => {
  setX(10);
  setY(20);
}); // Log: Sum: 30

Advanced Usage

Idioms and Patterns: Nested Batching

// Working with data fetching
const [loading, setLoading] = createSignal(false);
const [data, setData] = createSignal(null);
const [error, setError] = createSignal(null);

createEffect(() => {
  console.log({
    loading: loading(),
    hasData: !!data(),
    hasError: !!error(),
  });
});

createBatch(() => {
  setLoading(false);
  setData(fetchedData);
  setError(null);
});

Nested batches are supported:

const [a, setA] = createSignal(0);
const [b, setB] = createSignal(0);
const [c, setC] = createSignal(0);

createEffect(() => {
  console.log("Value:", a() * b() * c());
});

createBatch(() => {
  setA(1);

  createBatch(() => {
    setB(2);
    setC(3);
  });
});

Behavior

  • Batches can be nested - effects are deferred until the outermost batch completes

  • All effects are executed synchronously after the batch function completes

  • If an error occurs within the batch, effects are still flushed before the error propagates

  • Batching state is automatically restored even if the batch function throws an exception

Use Cases

  • 📝 Form Updates: Batch multiple form field updates to prevent intermediate validation states

  • 🔄 Data Loading: Update loading, data, and error states atomically

  • Animation: Coordinate multiple property changes for smooth transitions

  • 🚀 Performance: Reduce unnecessary effect executions in data-heavy operations

Performance Notes

When multiple signals are updated in sequence, each update would normally trigger all dependent effects immediately. createBatch() defers effect execution until all updates within the batch are complete, improving performance and preventing intermediate states from being observed.

Last updated