batch

A performance optimization that groups signal updates into a single effect run.

API

function batch<T>(batchFn: () => T): T
  • batchFn: A function that contains the signal updates to be batched.
  • Returns: The value returned by the function batchFn.

Basic Usage

By default, each signal update triggers its own effect run. With batch, all updates are grouped, and effects run only once.

import { signal, batch, effect } from '@hellajs/core';

const count = signal(1);
const multiplier = signal(2);

effect(() => {
  console.log(count() * multiplier())
});

batch(() => {
  count(2); // Effect doesn't run yet
  multiplier(3); // Effect doesn't run yet
});

// Effect runs once and logs 6

Key Concepts

Batch Boundaries

Batching only applies to synchronous signal updates within the batch function, async operations break batch boundaries.

import { signal, batch, effect } from '@hellajs/core';

const count = signal(1);
const multiplier = signal(2);

effect(() => {
  console.log(count() * multiplier())
});

batch(() => {
  setTimeout(() => multiplier(3), 0); // Not batched
  count(2); // Batched with count
});

// Effect runs twice and logs 4 and then 6

Nested Batching

Effects only run once the outermost batch completes, regardless of nesting depth.

import { signal, batch, effect } from '@hellajs/core';

const count = signal(0);
const multiplier = signal(1);

effect(() => {
  console.log(count() * multiplier());
});

function innerUpdate() {
  batch(() => {
    count(2);
    multiplier(2);
  });
}

batch(() => {
  count(1);       // count -> 1
  innerUpdate();  // count -> 2, multiplier -> 2
  multiplier(3);  // overwrite multiplier -> 3
});

// Effect runs once and logs 6