@molecule/app-state
v1.2.0
Published
Client state management interface for molecule.dev
Maintainers
Readme
@molecule/app-state
Client state management interface for molecule.dev.
Provides a unified state management API that works across different state management solutions (hooks, Zustand, Redux, Jotai, etc.).
Auto-generated, AI-first package reference for the molecule.dev ecosystem. It is written to be read by coding agents as much as by people, and is generated from this package's source — edit
src/index.tsJSDoc, not this file.
Quick Start
import { createStore, type Store } from '@molecule/app-state'
import { useStore } from '@molecule/app-react'
const initialState = { sidebarOpen: false }
// Created on first use, NOT at module scope — see the remarks above.
let uiStore: Store<typeof initialState> | undefined
const getUiStore = (): Store<typeof initialState> => (uiStore ??= createStore({ initialState }))
function Sidebar() {
const store = getUiStore()
const { sidebarOpen } = useStore(store) // subscribes to the store
const toggle = () => store.setState({ sidebarOpen: !sidebarOpen })
}Type
core
Installation
npm install @molecule/app-state @molecule/app-bond @molecule/app-loggerAPI
Interfaces
AsyncState
Async state tuple.
interface AsyncState<T> {
/**
* Current data value.
*/
data: T
/**
* Whether the state is loading.
*/
loading: boolean
/**
* Error if any occurred.
*/
error: Error | null
}AsyncStateActions
Async state actions.
interface AsyncStateActions<T> {
/**
* Sets the data value.
*/
setData(data: T): void
/**
* Sets the loading state.
*/
setLoading(loading: boolean): void
/**
* Sets an error.
*/
setError(error: Error | null): void
/**
* Resets to initial state.
*/
reset(): void
/**
* Executes an async operation, handling loading/error states.
*/
execute<R>(fn: () => Promise<R>): Promise<R>
}PersistStorage
Simple storage adapter interface for persist middleware.
Compatible with localStorage, sessionStorage, and
@molecule/app-storage providers.
interface PersistStorage {
getItem(key: string): string | null
setItem(key: string, value: string): void
}OptimisticValueOptions
Options for {@link createOptimisticValue}.
interface OptimisticValueOptions<T> {
/**
* The server's current value, for example `repository.starred` or
* `{ starred, stars }` from the record the page loaded.
*/
value: T
/**
* Saves one change (for example `next ? post(...) : delete(...)`). Only one save runs at a time;
* the next one starts after it settles.
*/
commit: OptimisticCommit<T>
/**
* Whether two values are the same change. Decides whether a save is needed and whether a new
* server value differs. Defaults to {@link shallowEqual}.
*/
equals?: (a: T, b: T) => boolean
/**
* Called when the newest change fails and the value has gone back to the server's value.
* A thrown callback error is logged without replacing the save failure.
*
* @param error - The rejection from {@link OptimisticValueOptions.commit}.
* @param value - The server's value now shown again.
*/
onError?: (error: unknown, value: T) => void
}OptimisticValueState
What to render.
interface OptimisticValueState<T> {
/** The newest value the person chose, or the server's value when nothing is being saved. */
value: T
/** Whether a save is running or waiting to run. */
pending: boolean
/** The failure of the newest change, after the value went back; `null` otherwise. */
error: unknown
}OptimisticValue
A value that the UI changes at once and saves in order.
interface OptimisticValue<T> {
/**
* The current state. The same object is returned until something changes, so it can be a
* `useSyncExternalStore` snapshot.
*
* @returns The current state.
*/
getState(): OptimisticValueState<T>
/**
* Shows `next` at once and saves it. A change made while a save runs is never dropped: it is
* saved after that save settles, and only the newest change is saved.
*
* @param next - The value the person chose.
*/
set(next: T): void
/**
* Like {@link OptimisticValue.set}, computed from the value shown now, so repeated taps build on
* each other (`update((on) => !on)`).
*
* @param change - Computes the next value from the value shown now.
*/
update(change: (current: T) => T): void
/**
* Takes a newer server value, for example new props after the page refetched. While a save runs,
* the value shown does not change; the new value is kept as the server's value and is shown if
* the save fails.
*
* @param value - The server's value.
*/
sync(value: T): void
/**
* Observes changes. Does not call the listener for the current state.
* Listener errors are logged and do not interrupt saves or other listeners.
*
* @param listener - Called with each new state.
* @returns Stops observing.
*/
subscribe(listener: (state: OptimisticValueState<T>) => void): () => void
/**
* Resolves once nothing is being saved.
*
* @returns The state at that moment.
*/
settled(): Promise<OptimisticValueState<T>>
}StoreConfig
Configuration for creating a store (initial state, optional name, and middleware chain).
interface StoreConfig<T> {
/**
* Initial state value.
*/
initialState: T
/**
* Optional name for debugging.
*/
name?: string
/**
* Optional middleware functions.
*/
middleware?: StoreMiddleware<T>[]
}Store
Reactive state container with getState, setState, subscribe, and destroy.
All state management providers must implement this interface.
interface Store<T> {
/**
* Gets the current state.
*/
getState(): T
/**
* Sets the state (partial or via updater function).
*/
setState(partial: Partial<T> | ((state: T) => Partial<T>)): void
/**
* Subscribes to state changes.
* Returns an unsubscribe function.
*/
subscribe(listener: StateListener<T>): () => void
/**
* Destroys the store and cleans up subscriptions.
*/
destroy(): void
}StateProvider
State provider interface that all state management bond packages must implement. Provides the store creation factory.
interface StateProvider {
/**
* Creates a new store.
*/
createStore<T>(config: StoreConfig<T>): Store<T>
}Types
OptimisticCommit
Saves one change on the server.
type OptimisticCommit<T> = (
next: T,
previous: T,
confirm: (change: (current: T) => T) => void,
) => Promise<T | void>next— The value to save.previous— The value the server held before this change, as far as the client knows.confirm— Records an acknowledged part of a multi-request save, without replacing the optimistic value. Pass an updater so unrelated refetched fields survive. If a later request fails, rollback and any queued save use this confirmed progress. Calls after this commit settles are ignored.
Returns: The server's value after the change, or nothing to keep next. Reject when the save fails. After calling confirm, returning nothing keeps the confirmed progress instead.
StoreMiddleware
Store middleware function. Wraps the set function to intercept
state updates (e.g. for logging, persistence, or devtools).
type StoreMiddleware<T> = (set: SetState<T>, get: GetState<T>) => SetState<T>set— The original setState function to wrap.get— A function returning the current state.
SetState
Function to update store state with a partial object or updater function.
type SetState<T> = (partial: Partial<T> | ((state: T) => Partial<T>)) => voidGetState
Get state function type.
type GetState<T> = () => TStateListener
Callback invoked whenever store state changes.
type StateListener<T> = (state: T, prevState: T) => voidstate— The new state after the update.prevState— The state before the update.
Selector
Selector function that derives a value from store state.
type Selector<T, S> = (state: T) => Sstate— The full store state to select from.
EqualityFn
Equality comparator for selectors. When provided, prevents re-renders if the selected value is equal to the previous one.
type EqualityFn<T> = (a: T, b: T) => booleanFunctions
createAsyncState(initialData)
Creates an async state container with loading/error tracking.
function createAsyncState<T>(initialData: T): [AsyncState<T>, AsyncStateActions<T>]initialData— The initial data value.
Returns: A tuple of [state, actions] for reading and updating the async state.
loggerMiddleware(name)
Logging middleware — logs previous and next state on every update.
function loggerMiddleware<T>(name?: string): StoreMiddleware<T>name— Optional store name for log prefix (defaults to'store').
Returns: A store middleware that logs state transitions.
persistMiddleware(key, storage)
Persist middleware — saves state to storage on every update and restores it on initialization.
Accepts any object implementing PersistStorage (getItem + setItem).
Defaults to in-memory storage.
function persistMiddleware<T>(key: string, storage?: PersistStorage): StoreMiddleware<T>key— The storage key to persist state under.storage— APersistStorage-compatible object (defaults to in-memory).
Returns: A store middleware that persists state to the given storage.
createOptimisticValue(options)
Creates a server-backed value that the UI changes at once and saves in order: a favorite, follow, like or bookmark button, a rating, a quantity, a setting switch.
A tap while a save runs is never ignored. Saves run one at a time, so the server receives the
changes in the order they were made, and when the person changes their mind several times
during one save, only the newest value is saved after it. When the newest change fails, the
value goes back to the server's value and error is set; a failure that a newer change has
already replaced is not shown.
function createOptimisticValue<T>(options: OptimisticValueOptions<T>): OptimisticValue<T>options— The server's current value and how to save a change.
Returns: The value's controller.
setProvider(provider)
Registers a state provider as the active singleton. Called by bond packages during application startup.
function setProvider(provider: StateProvider): voidprovider— The state provider implementation to bond.
getProvider()
Retrieves the bonded state provider, throwing if none is configured.
function getProvider(): StateProviderReturns: The bonded state provider.
hasProvider()
Checks whether a state provider is currently bonded.
function hasProvider(): booleanReturns: true if a state provider is bonded.
createStore(config)
Creates a new reactive state store using the bonded provider.
function createStore<T>(config: StoreConfig<T>): Store<T>config— Store configuration including initial state, actions, selectors, and middleware.
Returns: A reactive store instance with getState(), setState(), and subscribe() methods.
createSimpleStateProvider()
Creates a vanilla JavaScript state provider that manages stores with simple object spreading and listener-based subscriptions.
function createSimpleStateProvider(): StateProviderReturns: A StateProvider implementation.
combineStores(stores)
Combines multiple stores into a single composite store. Each key
in stores becomes a top-level key in the combined state.
function combineStores<T extends Record<string, unknown>>(stores: {
[K in keyof T]: Store<T[K]>
}): Store<T>stores— A record mapping keys to individual stores.
Returns: A composite Store that delegates to the individual stores.
shallowEqual(a, b)
Performs a shallow equality comparison between two values.
Returns true if both values have the same top-level keys
with identical values (using Object.is).
function shallowEqual<T>(a: T, b: T): booleana— First value to compare.b— Second value to compare.
Returns: true if the values are shallowly equal.
produce(state, recipe)
Simplified produce helper for immutable state updates. Creates a shallow copy, applies the recipe, and returns the result.
function produce<T extends object>(state: T, recipe: (draft: T) => void): Tstate— The current state object.recipe— A function that mutates the draft copy.
Returns: A new state object with the recipe's mutations applied.
Constants
simpleProvider
Pre-created default state provider instance.
const simpleProvider: StateProviderAvailable Providers
| Provider | Package |
| -------- | ----------------------------- |
| Jotai | @molecule/app-state-jotai |
| Redux | @molecule/app-state-redux |
| Zustand | @molecule/app-state-zustand |
Injection Notes
Requirements
Peer dependencies:
@molecule/app-bond^1.0.1@molecule/app-logger^1.0.1
Runtime Dependencies
@molecule/app-bond@molecule/app-logger
Define stores with {@link createStore} and read them through the framework hook
(useStore(store) in React / the Vue composable) — do NOT import zustand / redux /
jotai directly in a component; that couples you to one library and breaks the swap. For a
large store, pass a selector via the hook's options so a component re-renders only when the
slice it reads changes.
- This is CLIENT/UI state — NOT the source of truth for server data. Fetch server data
through the HTTP client (
@molecule/app-http) and keep the store for UI/session state. - A server-backed value the person toggles or sets (favorite, follow, like, bookmark,
rating, quantity, a setting switch) uses {@link createOptimisticValue} (React:
useOptimisticValuefrom@molecule/app-react). It shows each change at once, saves one change at a time in order, saves a change made during a save right after it, and goes back to the server value only when the newest change fails. Do not ignore taps while a request is pending, and do not let a refetch replace the value while a save runs. A commit containing multiple requests must call its third argument,confirm, after each successful request:confirm((current) => ({ ...current, [id]: saved })). Return nothing after recording progress. A later rejection then rolls back only unsaved changes, and a queued intent is compared with what the server actually accepted. - {@link persistMiddleware} persists to storage — never persist a secret or auth token
there (client storage is XSS-exfiltratable; the bearer token is memory-only — see
@molecule/app-storage). Persist only non-sensitive UI state, via the storage ABSTRACTION, never rawlocalStorage. - A state provider must be bonded before a store is created. In a scaffolded app that
is automatic:
setupAllDefaultBonds()(from@molecule/app-bonds-default-react, called byapp/src/bonds/index.ts'ssetupProviders()) bonds the vanillasimpleProvider, and the app's<MoleculeProvider>supplies the React contextuseStore()reads. To use another provider, bond it instead (e.g.@molecule/app-state-zustandwithsetProvider()) —createStore()call sites do not change. - Never create a store at module scope. Module bodies run before
setupProviders(), so a top-levelcreateStore()throws@molecule/app-state: No provider setat import time: every page renders blank whiletscpasses. Create it lazily (a getter the component calls) or inside the component, after the provider is set.
