batch
Edit this pagebatch groups multiple reactive updates so downstream computations run once after the batch completes instead of after each individual update.
Import
import { batch } from "solid-js";Type
function batch<T>(fn: () => T): T;Parameters
fn
- Type:
() => T - Required: Yes
Function executed inside the batch.
Return value
- Type:
T
Returns the value produced by fn.
Behavior
- Downstream computations are deferred until the batch completes.
- Nested
batchcalls behave like a single larger batch. - If you read a stale memo or signal inside the batch, Solid updates it on demand before returning the value.
- If
fnis asynchronous, batching applies only to updates before the firstawaitor other async suspension point.
Automatic batching
Solid automatically batches updates in several cases, including:
- inside
createEffectandonMount - inside the setter returned by
createStore - inside array mutation methods on
createMutable
Examples
Basic usage
const [count, setCount] = createSignal(0);const [total, setTotal] = createSignal(0);
const summary = createMemo(() => `${count()} / ${total()}`);createEffect(() => console.log(summary())); // logs "0 / 0"Outside batch:
setCount(1); // logs "1 / 0"setTotal(5); // logs "1 / 5"Inside batch:
batch(() => { setCount(1); setTotal(5);}); // logs "1 / 5"Read inside a batch
batch(() => { setCount(2); console.log(summary()); // logs "2 / 5" setTotal(10);}); // logs "2 / 10"