Introducing a new way to review your PRs.

Read the announcement

chakra-ui / zag

Build your design system in React, Solid, Vue, Svelte or Vanilla. Powered by finite state machines

View on GitHub

19 documents · Updated Sep 21, 2026

docs / machine-runtime

Machine runtime and service lifecycle

The machine runtime turns a declarative machine definition into a live service. It owns state, context, event handling, effects, and change notifications so that framework adapters can expose the same machine behavior to UI consumers. It is the runtime layer beneath the state machine platform and works with the definitions described in machine authoring.

Runtime model

The runtime combines a machine definition with user props and a framework-managed reactive store. The machine describes the allowed states and behavior. The adapter creates a service that runs that behavior in the host framework.

The definition can provide these core inputs:

  • An initial state chosen from the current props.
  • States with transitions, tags, entry actions, exit actions, and active effects.
  • Shared context for reactive values.
  • Guards that decide which transition can run.
  • Actions that change context or notify external code.
  • Computed values derived from the current service data.
  • Watches that react to tracked prop or context changes.

The core package validates and indexes the state tree when createMachine is called. This gives the runtime one model for nested states, state IDs, target paths, inherited transitions, and state tags across all adapters.

References: packages/…/create-machine.ts• L24-41 packages/…/state.ts• L33-80 packages/…/types.ts• L196-242

Service lifecycle

The service has three lifecycle statuses: not started, started, and stopped. Starting resolves the initial state and invokes it as an entry into the machine. Stopping releases active effects, runs the machine exit actions, and prevents later events from changing the service.

The lifecycle follows this sequence:

  1. The adapter creates props, scope, context, refs, computed access, and the initial state.
  2. The adapter marks the service as started.
  3. The runtime enters the initial state and runs root and state entry behavior.
  4. The service accepts events and publishes state or context changes to consumers.
  5. The adapter stops the service when its host component or owner is released.

The vanilla adapter exposes this lifecycle through explicit start and stop calls. UI adapters connect the same lifecycle to their host framework mount and unmount hooks. Their returned service shape stays consistent even though the scheduling and cleanup hooks belong to each framework.

flowchart TD
    A[Machine definition and props] --> B[Create service resources]
    B --> C[Start or mount]
    C --> D[Enter initial state]
    D --> E[Process events and changes]
    E --> F[Publish service snapshot]
    F --> E
    E --> G[Stop or unmount]
    G --> H[Clean up effects]
    H --> I[Run machine exit actions]
    I --> J[Reject later events]

References: packages/…/machine.ts• L87-123 packages/…/machine.ts• L310-331 packages/…/machine.ts• L290-317 packages/…/types.ts• L269-290

State interpretation

The runtime treats the current state as a path in a state tree. A path can include parent and child states. Entering or leaving a path also enters or leaves the relevant parent states, so parent behavior can cover a group of child states.

Transition lookup starts at the deepest active state. If that state has no matching event, the runtime checks its parents and then the machine-level event map. A target resolves to a sibling by default, to a child when it starts with ., or to a state ID when it starts with #. Compound states resolve their configured initial child.

State consumers can use either the full state path or a broader match. Tags provide a separate way to ask whether any active state in the path has a named capability.

References: packages/…/state.ts• L94-185 packages/…/state.ts• L192-248 packages/…/types.ts• L177-194

Event processing

send accepts an event object and routes it through the active state hierarchy. Events sent before a service is started or after it is stopped do not produce normal transitions. An event with no matching transition is a no-op.

For a matching event, the runtime selects the first transition whose guard passes. It then resolves the target and applies one of three behaviors:

  • A new target changes state and runs exit, transition, effect, and entry behavior.
  • A transition without a target runs its actions while keeping the current state.
  • A reenter transition leaves and enters the same state again. This restarts its entry actions and active effects.

The runtime records the current and previous events in the service snapshot. Actions, guards, effects, computed values, and watches receive a shared parameter set that can read props, context, refs, state, scope, and event data.

Most adapters defer event work to a microtask. This preserves ordered processing for several sends in one turn. Public setters can mark events with replaces so that a newer queued event for the same declarative value supersedes an older one. Internal events should not use that marker because they represent distinct system signals.

sequenceDiagram
    participant Consumer
    participant Service
    participant Machine
    participant Effects

    Consumer->>Service: send(event)
    Service->>Machine: find transition for active state
    Machine-->>Service: guarded transition or no match
    alt state target changes
        Service->>Effects: clean up exiting states
        Service->>Machine: run exit and transition actions
        Service->>Effects: start entering state effects
        Service->>Machine: run entry actions
    else internal transition
        Service->>Machine: run transition actions
    else reenter
        Service->>Effects: clean up current state effects
        Service->>Machine: run exit, transition, and entry behavior
    end
    Service-->>Consumer: publish updated snapshot

References: packages/…/machine.ts• L223-263 packages/…/machine.ts• L118-157 packages/…/machine.ts• L301-307 packages/…/replace-tracker.ts• L6-18

Action and guard behavior

Actions and guards are named behavior selected by the machine definition. The runtime resolves each name against the machine implementations and calls it with the current service parameters. A missing implementation does not create a transition or action; the runtime warns about the missing name.

Guards control transition choice. When several guarded transitions exist for one event, the runtime checks them in order and uses the first passing choice. If no guard passes, the event has no effect. Actions run in the order declared by the machine.

During a state change, the action order is stable:

  1. Actions for states that exit.
  2. Actions on the selected transition.
  3. Entry actions for states that enter.

Root entry and root effects run on the initial entry. Root exit actions run when the service stops.

References: packages/…/machine.ts• L265-307 packages/…/machine.ts• L168-205 packages/…/types.ts• L173-175 packages/…/machine.test.ts• L178-215

Effect management

Effects represent work that remains active while the machine or a state is active. An effect may return a cleanup function. The runtime stores cleanup by state path so it can stop the work when that path exits.

State effects start before the new state's entry actions. The runtime cleans up effects before exit actions when leaving a state. Reentering a state performs the same cleanup and setup cycle. Stopping the service cleans up all state and root effects, including effects that were started during initial entry.

Effects can send events back to the service. This lets timers, DOM listeners, observers, and other outside work drive the same transition path as consumer input. The cleanup contract is therefore important: an effect that does not release its outside work can send events after its state is no longer active.

References: packages/…/machine.ts• L168-205 packages/…/machine.ts• L285-299 packages/…/machine.ts• L317-330 packages/…/machine.test.ts• L518-595

Reactive context and derived data

Context is the machine's reactive data layer. A bindable context value can use a default value for uncontrolled use or a prop-backed value for controlled use. Actions update context through the service, while consumers read it through the service snapshot.

Computed values are read-only derivations over props, context, refs, scope, and events. Watches connect selected changes to actions. The runtime tracks the dependencies supplied by a watch and calls its action only when the dependency values change.

Context and state changes publish a fresh service view to subscribers. Framework adapters use that signal to update their consumers while keeping the machine definition framework independent.

References: packages/…/types.ts• L34-65 packages/…/machine.ts• L125-162 packages/…/machine.ts• L357-396 packages/…/machine.ts• L160-188

Consumer snapshot

The service is the runtime's consumer-facing snapshot. It exposes the current state and helpers together with the data and capabilities needed by component code.

Snapshot areaConsumer purpose
stateRead the current path, test matches, and check tags.
contextRead or update machine-owned reactive values.
sendDeliver an event to the machine.
eventRead the current and previous event.
propRead normalized machine props.
computedRead derived machine values.
refsAccess non-reactive machine references.
scopeResolve the machine's DOM and identity scope.
getStatusCheck whether the service is started or stopped.

The vanilla service can notify direct subscribers after state or context changes. UI adapters return the same service contract through their framework hooks, so component connectors can consume machine behavior without knowing which runtime adapter is active.

References: packages/…/types.ts• L269-285 packages/…/machine.ts• L333-360 packages/…/machine.ts• L326-336

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the Service contract aligned with each framework adapter so state, event, context, and status have the same meaning.
  • Keep state target resolution and transition lookup changes aligned with nested state types and state-index validation.
  • Preserve effect cleanup ownership by state path when changing entry, exit, reenter, or stop behavior.
  • Preserve queued-event ordering and replaces semantics when changing any adapter's send path.
  • Keep controlled context behavior aligned with bindable values so a local write does not appear as a committed change when props own the value.
  • Keep subscriber publication aligned with both state changes and context changes so consumers do not receive stale snapshots.

Important failure modes

TriggerConsequenceGuard
A compound state has no valid initial childThe machine cannot resolve a complete active state path.Validate the state tree during createMachine.
Several queued public setter events use the same value slot without replacesAn older event can apply after a newer intent.Mark only declarative public setter events with the shared replacement key.
An effect does not return or run its cleanupOutside listeners or timers can remain active after state exit.Store cleanup by state path and run it on exit, reenter, and stop.
A transition list has no passing guardThe event leaves state and context unchanged.Add an unguarded fallback when the event must always have a valid path.
An event is sent after service stopThe event is ignored and no consumer update occurs.Check service status before relying on a send.
A named action, guard, or effect has no implementationThe named behavior does not run and the runtime warns.Keep definition names and implementation maps synchronized.

Key files

FileWhy to read it
packages/…/types.tsDefines the machine schema, transition model, service snapshot, and lifecycle statuses.
packages/…/state.tsExplains state-tree indexing, target resolution, transition lookup, and exit/entry calculation.
packages/…/create-machine.tsShows how machine definitions are created and validated before runtime use.
packages/…/machine.tsShows the clearest explicit service lifecycle and event processing flow.
packages/…/machine.tsShows how the shared runtime model connects to a component lifecycle and reactive rendering.
packages/…/machine.tsShows pre-mount event buffering and replay for a framework with parent-child mount order concerns.
packages/…/replace-tracker.tsDefines last-event-wins behavior for replaceable queued events.
packages/…/machine.test.tsSummarizes the runtime guarantees for lifecycle, action order, guards, effects, snapshots, and queued events.