coaction
v4.0.0
Published
A sleek JavaScript library designed for high-performance and multithreading web apps.
Readme
coaction
An efficient and flexible state management library for building high-performance, multithreading web applications.
Coaction uses alien-signals internally for cached getter/computed state, React selector reactivity, and adapter-facing subscriptions. The core package also re-exports the signal primitives for advanced integrations.
Coaction 4.0 pins the qualified alien-signals runtime to 3.1.2. Use the
primitives exported by coaction for integrations so they share the store's
reactive graph. Upgrading this internal runtime requires compatibility checks
for both subscriptions and the exported signal APIs.
Installation
Install it with pnpm:
pnpm add coactionUsage
import { create } from 'coaction';
const store = create((set) => ({
count: 0,
get doubleCount() {
return this.count * 2;
},
increment() {
set(() => {
this.count += 1;
});
}
}));Core stores are immutable by default. Getters and methods can read through this, but writes to Coaction-owned state must happen inside set() or set((draft) => ...). Direct writes such as this.count += 1 in a store method throw because they bypass the commit path that notifies subscribers, produces patches when enabled, and synchronizes worker/client mirrors in shared mode.
Coaction fixes the public state schema after initialization. A single store cannot add new top-level state keys later, and a slices store cannot add new slice keys or new top-level fields inside a slice. Replacement-style APIs such as apply() may omit a known single-store root key; the public getter remains present and reads as undefined, but no unknown key is promoted into the public module. Slice root keys are stricter and cannot be removed or replaced with non-object values. Keep dynamic data inside an existing object or array field.
Mutable adapters such as MobX, Pinia, and Valtio keep Coaction raw state, public state, and the external mutable runtime synchronized for known schema keys. Coaction still treats its raw/public schema as authoritative: out-of-band unknown properties written directly onto a third-party mutable runtime are not promoted into Coaction state, and adapter-specific docs define whether that external runtime property is pruned, restored, or left to the underlying library.
Accessor getters are cached automatically through the built-in signal runtime. Use get(deps, selector) when you want to declare dependencies manually:
const store = create((set, get) => ({
count: 0,
doubleCount: get(
(state) => [state.count],
(count) => count * 2
),
increment() {
set(() => {
this.count += 1;
});
}
}));Local stores can import signal primitives from coaction. Adapter authors use
the statically separate coaction/adapter entry:
import { computed, effect, signal } from 'coaction';
import { defineExternalStoreAdapter } from 'coaction/adapter';Optional managed derivations
Native getters read frozen snapshots at a store/slice field boundary. For an exact path or a selector with explicit deep value tracking, use the separate entry:
import { derive, derivePath } from 'coaction/derived';
const count = derivePath(store, ['count']);
const doubled = derive(store, (state) => state.count * 2, { deep: true });derive defaults to conservative object identity dependencies; deep mode requires
identity(value) for identity comparisons and opaque captures. Returned state in
plain data wrappers is tracked automatically. Results default to Object.is, with
an optional pure equals comparator. Reads inside recipes see drafts without
changing the committed cache. Call .dispose() when the owner finishes, or
store.destroy() to release its derivations. Define these outside React render.
Native getters remain the efficient frozen-snapshot option for full scans.
See the computed guide
for identity, output, transaction and lifecycle contracts.
Adapter and Middleware Utilities
coaction/adapter exports utilities for adapter and middleware authors. These are not needed for normal application state updates, but they are part of the supported integration surface used by the official packages:
- Mutable adapter helpers:
applyMutableAdapterPatches,replaceMutableAdapterState,toMutableAdapterSnapshot,snapshotMutableAdapterPureState,isEqualMutableAdapterSnapshot,getMutableAdapterOwnEnumerableKeys,isMutableAdapterUnsafeKey. - Root replacement helpers:
createRootReplacementPatches,applyRootReplacementWithPatches. - Patch safety helpers:
assertSafePatches,sanitizePatches,UnsafePatchPathError. - State shape helpers:
StateSchemaError,isStateSchemaError,sanitizeReplacementState,sanitizeInitialStateValue,replaceOwnEnumerable.
Runtime mutation paths reject unsafe patch paths before applying state changes. If a store.patch() hook returns a path containing __proto__, prototype, or constructor, Coaction throws UnsafePatchPathError instead of silently dropping that patch and applying the rest.
Shared JSON contract
Import create from coaction/shared when state crosses a Worker,
SharedWorker, or injected transport boundary:
import { create } from 'coaction/shared';Shared state, action arguments, action results, patch values, and full-sync
snapshots must be JSON trees: finite numbers, strings, booleans, null, dense
arrays, and plain records. Coaction rejects values that JSON would normalize or
cannot represent losslessly, including undefined, BigInt, NaN, infinity,
negative zero, functions in data, symbols, accessors, platform objects, sparse
arrays, circular references, and repeated object references. Local stores do
not inherit this restriction.
Local initialization and complete value replacement can preserve cycles and
shared references. Native setState(recipe) still uses Mutative drafts:
creating cycles from draft references or editing inside cyclic drafts is
unsupported. Build a complete new graph from ordinary objects and replace its
field with setState({ node: nextNode }), or replace a cyclic root with
apply(nextState). A recipe may assign that complete value. Do not mutate it
after handing it to the store.
Acyclic shared nodes use independent drafts for each path. Editing
draft.left.value need not update draft.right.value; explicitly assign
draft.right = draft.left to share the result. Commit replay and history
preserve the resulting topology, using full snapshots when required.
An authority and every connected client must use the same Coaction major and wire protocol. Mixed-major shared deployments are unsupported.
Store methods using this are rebound to the latest state when invoked from getState(), so destructuring remains safe:
const store = create((set) => ({
count: 0,
increment() {
set(() => {
this.count += 1;
});
}
}));
const { increment } = store.getState();
increment();API Reference
Store Shape Mode (sliceMode)
create() uses sliceMode: 'auto' by default. For backward compatibility, auto still treats a non-empty object whose enumerable values are all functions as slices. That shape is ambiguous with a plain store that only contains methods, so development builds warn and you should set sliceMode explicitly.
You can force behavior explicitly:
sliceMode: 'single': treat object input as a single store.sliceMode: 'slices': require object-of-slice-functions input.
create({ ping: () => 'pong' }, { sliceMode: 'single' });
create({ counter: (set) => ({ count: 0 }) }, { sliceMode: 'slices' });Documentation
You can find the documentation here.
