Skip to content

StateMeshTransaction-first state for React

Every state change is a transaction. Optimistic UI, rollback, retry, undo/redo, time travel, routing, forms, persistence, cross-tab sync — all automatic. Zero dependencies. One mesh.

StateMesh Logo

Quick Start

bash
npm install statemesh-core
tsx
import { createMesh, StateMeshProvider, useMeshState } from "statemesh-core";

const mesh = createMesh({
  state: { count: 0 }
});

function Counter() {
  const [count, setCount] = useMeshState<number>("count");
  return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}

export function App() {
  return (
    <StateMeshProvider mesh={mesh}>
      <Counter />
    </StateMeshProvider>
  );
}

Why StateMesh?

Every state change is a transaction

StateMesh treats every mutation — button clicks, API calls, form submissions, route transitions — as a transaction with a built-in lifecycle. You get optimistic UI, automatic rollback, retry with backoff, timeout, and cancellation without writing any boilerplate.

ts
mesh.transaction("cart.checkout", {
  optimistic(state) { state.cart.status = "processing"; },
  async effect(state, payload, ctx) {
    return fetch("/api/checkout", { signal: ctx.signal });
  },
  commit(state, result) { state.order = result; },
  rollback: true,           // Auto-rollback on failure
  retry: { attempts: 3, delay: backoff() }
});

One store for everything

State, server cache, forms, URL parameters, cross-tab sync, undo history — all live in one store with one set of types. No more wiring together 5 libraries with different mental models.

ts
const mesh = createMesh({ state: { /* app state */ } });

mesh.action("cart.addItem", addItemHandler);     // State mutations
mesh.resource("products.list", productsDef);      // Server cache
mesh.form("checkout.form", checkoutFormDef);       // Forms
mesh.urlState("filters", filterDefaults);          // URL state
mesh.persist({ keys: ["theme", "cart"] });         // Persistence
mesh.use(tabSyncPlugin({ keys: ["cart"] }));       // Cross-tab sync
mesh.undo({ maxHistory: 50 });                     // Undo/redo

Subscriptions that never waste renders

Path-scoped selectors with equality checking. Updating cart.items does not rerender components reading theme. Computed values cache until their dependencies change. Resources deduplicate in-flight requests by key.

tsx
// Only re-renders when cart.items.length actually changes
const count = useMeshSelector((state) => state.cart.items.length);

Undo, redo, and time travel — for free

Opt-in state history with configurable depth. Replay to any point in time. Batch-aware grouping so multi-step operations undo as one.

ts
mesh.undo();                          // Go back
mesh.redo();                          // Go forward
mesh.enableTimeTravel();
mesh.replayToTimestamp(Date.now() - 5000);  // 5 seconds ago

Routing that IS state management

Every route transition is a transaction. Every loader is a resource. Every guard is middleware. Navigation rollback, keep-alive pools, and predictive prefetch — all sharing the same store.

Built-in DevTools

Timeline, profiler, diagnostics, state inspector, resource cache viewer, form debugger, and event log — all in a dockable panel. Mask sensitive paths. Export debug reports.

Production-grade from day one

  • Zero runtime dependencies — React is the only peer dependency
  • 100% TypeScript — type-safe paths, discriminated events, generic inference
  • SSR-safe — all browser APIs guarded, dehydrate/hydrate for server rendering
  • 603 tests — every module, API surface, error path, and edge case covered
  • Tree-shakeable — router, devtools, and testing are separate entry points
  • Bounded memory — LRU caches, ring buffers, snapshot limits

Documentation

Getting Started

Getting StartedInstall, create your first mesh, render in React
Core ConceptsStore, paths, subscriptions, actions, transactions
TypeScriptType-safe state, events, paths, and generic inference

Core

StateCreate stores, read/write state, path-based access
ActionsNamed state mutations with payloads and handlers
Selectors & ComputedDerived state, memoization, dependency tracking
Batch OperationsGroup multiple updates into a single notification
TransactionsAsync lifecycle — validate, optimistic, effect, commit, rollback
Undo / RedoAutomatic history tracking with configurable depth
Time TravelReplay to any point in time, snapshot inspection
Middleware PipelinesIntercept, transform, log, and guard state changes

Data

ResourcesCached API reads with deduplication, polling, pagination
MutationsWrite operations with optimistic rollback and offline queue
API ClientBuilt-in HTTP client with interceptors and retry
PersistencelocalStorage, sessionStorage, IndexedDB, cross-tab sync

UI Integration

FormsAsync validation, schema adapters, field arrays, autosave
URL StateSync state with URL search params — read, write, share
Error BoundariesCatch and handle errors at the component level

Router

OverviewRouting IS state management — setup and configuration
RoutesDefine routes, nested layouts, dynamic params, Outlet
NavigationProgrammatic navigation, Link component, preload, SharedElement
Guards & MiddlewareProtect routes, redirect, auth checks, navigation guards
Data LoadingLoaders, resources, Suspense, error handling
AdvancedKeep-alive pools, predictive prefetch, parallel routes
SEO & MetaDynamic meta tags, Open Graph, structured data

Advanced

MiddlewareIntercept actions, transactions, and state changes
GuardsProtect operations with async validation
PluginsExtend mesh with custom functionality
Cross-Tab SyncBroadcastChannel sync across browser tabs
DevToolsTimeline, profiler, diagnostics, state inspector
Dehydrate & HydrateSSR support — serialize state on server, hydrate on client
PerformanceProfiling, optimization tips, memory management

Testing

SetupTest helpers, mock mesh, async utilities
PatternsUnit tests, integration tests, transaction testing

Integration

Next.jsServer components, SSR, app router integration
MigrationMigrate from Redux, Zustand, Jotai, React Query

Reference

ErrorsError codes, messages, and troubleshooting
EventsEvent types, payloads, and subscription patterns
ChangelogVersion history and breaking changes
ContributingDevelopment setup, PR guidelines, code style
SecuritySecurity policy and vulnerability reporting

Released under the MIT License.