Machine actions
State machines are built in. You declare modes, allowed transitions, and optional onEnter / onExit hooks; the library validates every transition and stamps a state[machineName].mode field. Every transition is dispatched as an action tuple — same dispatch path as everything else.
Try it
Section titled “Try it”A classic traffic light: three modes, strict ordering. Each control dispatches a machine/... tuple — recorded below.
redDispatched machine actions
- Click a control to see the action tuple.
Things to notice:
- Valid transitions only.
red → green → yellow → redis allowed; the buttons for the other directions are disabled becauseuseStateMachineexposesallowedTransitions. forcebypasses the validator. Sometimes you need to jump modes for recovery or testing.sequenceis a single tuple that walks the machine through multiple modes, firingonEnterper step.
Define a machine
Section titled “Define a machine”A machine is plain data — a StateMachineDefinition object. Drop it on the provider.
import type { StateMachineDefinition } from '@input-actions/core';
const trafficLight: StateMachineDefinition = { name: 'light', initialState: 'red', states: { red: { allowedTransitions: ['green'] }, green: { allowedTransitions: ['yellow'] }, yellow: { allowedTransitions: ['red'] }, },};import { StoreProvider, createSimpleStore } from '@input-actions/core';
const store = createSimpleStore({ light: { mode: 'red' } });
<StoreProvider store={store} stateMachines={[trafficLight]}> <App /></StoreProvider>Machine state lives at state[machineName].mode. If state has no mode for a machine yet, its definition’s initialState is used — for useStateMachine, for bindings, and as the from state of the first transition, which then writes the slice. A mode already in state (seeded or hydrated) always wins. Seeding the slice explicitly is still fine and keeps useStore(s => s.light.mode) defined from the first render.
machine/transition
Section titled “machine/transition”['machine/transition', machineName, targetMode, ...sideEffects: Action[]]The default. Validates the transition against allowedTransitions; if allowed, dispatches ['action/save', [machineName, 'mode'], targetMode] plus any onEnter / onExit actions plus the inline sideEffects. If denied, writes the error to state[machineName].error and leaves the mode alone.
const actions = useActions();
<button onClick={actions(['machine/transition', 'light', 'green'])}> Go</button>Inline side effects fire as part of the same transition:
[ 'machine/transition', 'wizard', 'reviewing', ['action/save', ['lastReviewedAt'], Date.now()],]machine/transition-if
Section titled “machine/transition-if”['machine/transition-if', machineName, targetMode, successActions: Action[], fallbackActions: Action[]]Conditional dispatch. Fires successActions if the transition is allowed, fallbackActions otherwise. Use it when downstream behaviour should differ on the validator’s answer.
[ 'machine/transition-if', 'checkout', 'paid', [['action/save', ['notice'], 'Order placed!']], // on success [['action/save', ['notice'], 'Please complete payment first.']],]machine/force
Section titled “machine/force”['machine/force', machineName, targetMode, ...sideEffects: Action[]]Bypass the validator. Useful for:
- Recovery flows (jump back to
idlefrom any error state). - Test setups (skip past a long path).
- Devtools wiring.
Use sparingly. The point of an FSM is that transitions are constrained; reaching for force is opting out of that contract.
['machine/force', 'wizard', 'editing']machine/sequence
Section titled “machine/sequence”['machine/sequence', machineName, steps: Array<{mode: string, actions?: Action[]}>]Walk the machine through multiple modes in one tuple. Each step:
- Validates the transition from the current mode.
- Fires
onExitfor the leaving mode, thenonEnterfor the entering mode (ADR 0012). - Dispatches the step’s optional
actionsarray.
[ 'machine/sequence', 'wizard', [ { mode: 'reviewing' }, { mode: 'submitted', actions: [['action/save', ['submittedAt'], Date.now()]] }, ],]The whole sequence is validated before anything runs. If any step is invalid, nothing is committed, and the error (Sequence failed at step N: ...) is written to the machine slice.
Validation sees what earlier steps write. Each step’s sync writes (its onExit/onEnter and its actions, including inside batches) are applied to a projected copy of state before the next step is checked. So a later invariant can depend on an earlier step:
// payment's onEnter saves ['payment', 'method']; confirmed's invariant needs it.['machine/sequence', 'checkout', [{ mode: 'payment' }, { mode: 'processing' }, { mode: 'confirmed' }]]Async results aren’t projected, since they arrive later. A step’s own actions run after its invariant is checked, the same as with machine/transition. In a global store, a projected action/reset leaves the value unchanged, because the store doesn’t expose its initial state (ADR 0012).
machine/retry
Section titled “machine/retry”['machine/retry', machineName, targetMode, maxRetries: number, retryActions: Action[]]Try the transition up to maxRetries times, with exponential backoff between attempts (1s, 2s, 4s, …). On the attempt that succeeds, the transition’s onExit / onEnter run, then retryActions. If every attempt fails, state[machineName].error is set to Retry limit exceeded after N attempts. Useful when a transition’s invariants depend on state that something else is about to fill in.
[ 'machine/retry', 'connection', 'connected', 3, // up to 3 attempts [['action/save', ['ui', 'banner'], null]] // runs once connected]The attempt count is kept by the provider, not in state. The validator’s invariants run on every attempt, so you can gate retries on derived state. Backoff timers belong to the provider (cleared on unmount) and to the current state visit: if the machine changes mode while a retry is waiting, the retry is abandoned and its count reset.
machine/delay
Section titled “machine/delay”['machine/delay', machineName, targetMode, delayMs: number, delayedActions: Action[]]Schedule the transition + follow-ups after delayMs. Returns synchronously; the actual transition fires from a timer that the provider tracks and clears on unmount.
The timer belongs to the state visit that scheduled it. If the machine changes mode before it fires — including leaving and coming back to the same state — the delayed transition is dropped silently, rather than firing from the wrong state and writing an error. A state that arms a delay in its onEnter therefore gets a fresh timer on every entry.
[ 'machine/delay', 'toast', 'hidden', 3000, [['action/save', ['ui', 'lastDismissed'], 'auto']],]Useful for auto-dismissing notifications, timed transitions, and “after N ms idle, do X” patterns. No useEffect cleanup to write — the provider handles the timer.
onEnter / onExit hooks
Section titled “onEnter / onExit hooks”Each mode can declare action arrays that fire when entering or leaving it. The library dispatches them as part of any transition into / out of that mode (including from sequence, force, etc.).
const checkout: StateMachineDefinition = { name: 'checkout', initialState: 'cart', states: { cart: { allowedTransitions: ['shipping'] }, shipping: { allowedTransitions: ['payment'], onEnter: [['action/async', 'fetch-rates', 'fetchShippingRates']], onExit: [['action/save', ['shipping', 'committed'], true]], }, payment: { allowedTransitions: ['confirmed'] }, confirmed: { allowedTransitions: [], onEnter: [['action/async', 'flush-cart', 'submitOrder', { strategy: 'prevent' }]], }, },};Hooks fire as part of the transition — same dispatch tick. The chat example uses onEnter('connected') to drain its offline outbox:
connected: { allowedTransitions: ['disconnected', 'reconnecting'], onEnter: [ ['action/async', 'flush-outbox', 'flushOutbox', { strategy: 'allow' }], ],},Invariants
Section titled “Invariants”Per-state predicates that gate entry. The transition is denied if the invariant returns a non-null string (which becomes the error message).
states: { payment: { allowedTransitions: ['confirmed'], invariants: (state) => state.payment?.token ? null : 'Payment token required', },},Useful when “you can only enter mode X if the state already satisfies Y” — order is filled before payment, cart is non-empty before checkout. Keeps that rule next to the mode that depends on it instead of scattered around dispatch sites.
useStateMachine
Section titled “useStateMachine”Read-side hook. Returns the current mode plus the validator’s view of what’s allowed next.
import { useStateMachine } from '@input-actions/core';
function Controls() { const { currentMode, allowedTransitions, canTransitionTo, validateTransition } = useStateMachine('light'); // ...}It returns a MachineView:
| Field | Value |
|---|---|
currentMode | The mode this render shows (initialState before the first transition). |
error | The last rejected transition’s message, cleared by the next successful one. |
allowedTransitions | Modes currentMode declares it can move to. Invariants aren’t checked. |
canTransitionTo(mode) | Whether a transition to mode would be accepted now. |
validateTransition(mode) | The full result, including the invariant’s error message. |
Use canTransitionTo to disable buttons. Use validateTransition if you need the validator’s error message ahead of dispatching.
The fields describe the render; the two methods check against the latest state when you call them. So a click handler asks the same question the transition it’s about to dispatch will, even if an invariant reads state this component doesn’t subscribe to.
useStateMachine re-renders only when that machine’s slice changes. Like any hook, it can’t be called in a loop or a condition. To pick machines at render time, use useMachines, which returns getMachine(name) for any configured machine and re-renders when any of them changes:
import { useMachines } from '@input-actions/core';
function MachineList({ names }: { names: string[] }) { const { getMachine } = useMachines(); return names.map((name) => <li key={name}>{name}: {getMachine(name).currentMode}</li>);}useMachines is @beta.
Machines and bindings
Section titled “Machines and bindings”The bindings layer has a machine-aware variant. useBoundActions(id) can return different event maps based on currentMode, so JSX renders mode-appropriate controls without per-mode conditionals. See the bindings quickstart and ADR 0022.
Machines are deliberately flat: named modes, allowed edges, entry invariants and onEnter/onExit hooks over your store. Transitions name their target, not an event. There are no nested, parallel or final states, no per-edge guards, and no machine-owned context. Each has an equivalent here:
- Events per mode: machine-rooted bindings.
- Per-edge guards:
invariantsortransition-if. - Parallel regions: one machine each.
- Final states:
allowedTransitions: []. aftertransitions:machine/delayinonEnter.
If you need full statecharts, use XState. See ADR 0027.
Local machines
Section titled “Local machines”useLocalActions accepts machines too — same shape, third argument:
const { state, actions, getMachine } = useLocalActions( { wizard: { mode: 'editing' } }, {}, // asyncHandlers [wizardMachine], // stateMachines);The local getMachine(name) returns the same MachineView as the global useStateMachine hook. It’s a function rather than a hook because useLocalActions already re-renders on every change, so it follows the same pattern as getBoundActions (local) and useBoundActions (global). Test machine logic in isolation; promote to a global store when it needs to be shared.
See it in action
Section titled “See it in action”The chat example drives its connection lifecycle through a machine, including onEnter('connected') outbox flushing. The bindings example includes a small wizard that pairs the FSM with machine-rooted bindings.