Skip to content

Performance

StateMesh is designed for performance. This guide covers the built-in optimizations and best practices.

Built-in Optimizations

Path-Scoped Subscriptions

Subscriptions are equality-checked and path-scoped. Only relevant subscribers re-render:

ts
// Updating cart.items does NOT trigger subscribers reading theme
mesh.setPath("cart.items", [...items, newItem]);

Batch Operations

Group multiple updates into one notification:

ts
mesh.batch(() => {
  mesh.setPath("a", 1);
  mesh.setPath("b", 2);
  mesh.setPath("c", 3);
});
// Subscribers fire once

Action Skip

Actions that produce the same state (checked via shallowEqual) skip the clone-and-commit cycle entirely.

Resource Deduplication

Multiple components fetching the same resource with the same params share a single network request.

Computed Caching

Computed values cache until their dependencies change. Multiple reads return the same cached result.

Path Tokenization Cache

Repeated path.split('.') calls are cached per path string.

Stable Status References

getResourceStatus, getTransactionStatus, and getMutationStatus return the same object reference when the underlying state hasn't changed.

createSelector

Use createSelector for expensive selectors:

ts
import { createSelector } from "statemesh-core";

const selectFilteredProducts = createSelector(
  (state) => state.products,
  (state) => state.filters,
  (products, filters) => {
    // Expensive filtering/sorting
    return products.filter(/* ... */).sort(/* ... */);
  }
);

Only recomputes when products or filters changes.

Profiler

Record performance samples:

ts
const slowOps = mesh.getProfilerSamples({
  slowOnly: true,
  minDuration: 16  // ms
});

Best Practices

TIP

Use path-based subscriptions. useMeshState("cart.count") is more efficient than useMeshSelector(s => s.cart.count) for simple paths.

TIP

Batch related updates. If you update 5 paths in response to one event, wrap them in mesh.batch().

TIP

Use staleTime on resources. Prevent unnecessary refetches when data is still fresh.

TIP

Use maxCacheEntries on resources. Bound memory usage for list/search resources.

WARNING

Avoid deep-cloning large state. Undo/redo and time travel store deep clones. Use paths to limit what's tracked.

TIP

Use keepPreviousData on resources. Prevent loading spinners during pagination/filter changes.

Next Steps

Released under the MIT License.