Skip to content

Batch Operations

mesh.batch groups multiple state mutations into a single subscription notification. Without batching, each setState or setPath call triggers subscribers immediately. With batching, subscribers are notified once after all mutations complete.

Why Batch?

ts
// Without batch — 3 separate notifications, 3 re-renders
mesh.setPath("cart.status", "processing");
mesh.setPath("cart.error", null);
mesh.setPath("ui.checkoutDisabled", true);

// With batch — 1 notification, 1 re-render
mesh.batch(() => {
  mesh.setPath("cart.status", "processing");
  mesh.setPath("cart.error", null);
  mesh.setPath("ui.checkoutDisabled", true);
});

Usage

ts
mesh.batch(() => {
  mesh.setPath("theme", "dark");
  mesh.setPath("fontSize", 18);
  mesh.setPath("sidebar.collapsed", true);
});
// Subscribers fire once here, with all 3 changes applied

Batch with Mesh Reference

The callback receives the mesh itself, so you can use mesh methods directly:

ts
mesh.batch((m) => {
  m.setPath("cart.status", "processing");
  m.setPath("cart.error", null);
  m.setPath("ui.checkoutButton", "disabled");
});

Batch with Actions

Actions inside a batch are coalesced:

ts
mesh.batch(() => {
  setTheme("dark");
  setFontSize(18);
  toggleSidebar();
});

Error Handling

If the callback throws, no state changes from the batch take effect:

ts
mesh.batch(() => {
  mesh.setPath("a", 1);
  mesh.setPath("b", 2);
  throw new Error("oops"); // a and b are NOT updated
});

React Hook

Use useMeshBatch for a stable batch callback in components:

tsx
import { useMeshBatch } from "statemesh-core";

function SettingsPanel() {
  const batch = useMeshBatch();

  return (
    <button onClick={() => batch(() => {
      mesh.setPath("theme", "dark");
      mesh.setPath("fontSize", 16);
    })}>
      Apply Settings
    </button>
  );
}

Batch and Undo/Redo

When undo/redo is enabled, multiple mutations inside a batch() are captured as a single undo entry:

ts
mesh.batch(() => {
  mesh.setPath("cart.items", [...items, newItem]);
  mesh.setPath("cart.count", items.length + 1);
});

mesh.undo(); // Reverts both changes at once

Important Notes

TIP

Batching is useful when different subsystems or actions need to update related state without intermediate re-renders.

WARNING

Nested batches are supported. The outer batch controls when subscribers are notified. The inner batch increments a depth counter.

TIP

Batch also works with actions, transactions (for the optimistic phase), and other mesh methods that mutate state.

Next Steps

Released under the MIT License.