Quick Start bash npm install statemesh-core 1
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 >
);
} 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
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 () }
}); 1 2 3 4 5 6 7 8 9
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 1 2 3 4 5 6 7 8 9
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 ); 1 2
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 1 2 3 4
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.
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 dependency100% TypeScript — type-safe paths, discriminated events, generic inferenceSSR-safe — all browser APIs guarded, dehydrate/hydrate for server rendering603 tests — every module, API surface, error path, and edge case coveredTree-shakeable — router, devtools, and testing are separate entry pointsBounded memory — LRU caches, ring buffers, snapshot limitsDocumentation Getting Started Core State Create stores, read/write state, path-based access Actions Named state mutations with payloads and handlers Selectors & Computed Derived state, memoization, dependency tracking Batch Operations Group multiple updates into a single notification Transactions Async lifecycle — validate, optimistic, effect, commit, rollback Undo / Redo Automatic history tracking with configurable depth Time Travel Replay to any point in time, snapshot inspection Middleware Pipelines Intercept, transform, log, and guard state changes
Data Resources Cached API reads with deduplication, polling, pagination Mutations Write operations with optimistic rollback and offline queue API Client Built-in HTTP client with interceptors and retry Persistence localStorage, sessionStorage, IndexedDB, cross-tab sync
UI Integration Forms Async validation, schema adapters, field arrays, autosave URL State Sync state with URL search params — read, write, share Error Boundaries Catch and handle errors at the component level
Router Overview Routing IS state management — setup and configuration Routes Define routes, nested layouts, dynamic params, Outlet Navigation Programmatic navigation, Link component, preload, SharedElement Guards & Middleware Protect routes, redirect, auth checks, navigation guards Data Loading Loaders, resources, Suspense, error handling Advanced Keep-alive pools, predictive prefetch, parallel routes SEO & Meta Dynamic meta tags, Open Graph, structured data
Advanced Middleware Intercept actions, transactions, and state changes Guards Protect operations with async validation Plugins Extend mesh with custom functionality Cross-Tab Sync BroadcastChannel sync across browser tabs DevTools Timeline, profiler, diagnostics, state inspector Dehydrate & Hydrate SSR support — serialize state on server, hydrate on client Performance Profiling, optimization tips, memory management
Testing Setup Test helpers, mock mesh, async utilities Patterns Unit tests, integration tests, transaction testing
Integration Next.js Server components, SSR, app router integration Migration Migrate from Redux, Zustand, Jotai, React Query
Reference Errors Error codes, messages, and troubleshooting Events Event types, payloads, and subscription patterns Changelog Version history and breaking changes Contributing Development setup, PR guidelines, code style Security Security policy and vulnerability reporting