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-authoring

Machine definitions and interaction contracts

Machine definitions describe the behavior of a component without tying it to a UI framework. They turn props and events into state changes, context updates, side effects, and a small public API that component packages can use to render accessible UI. See also State machine platform, Machine runtime, and Component machines.

Machine definition model

The machine is the behavior contract for one component. A component package supplies a typed schema and a machine definition, while a framework adapter runs the definition and a connect function turns the running service into DOM props and public methods.

The main parts have separate roles:

PartPurpose
PropsExternal configuration and callbacks. The machine can normalize defaults before use.
StateA finite behavior mode. Transitions move the machine between named states.
ContextReactive values that change during the machine lifetime.
RefsNon-reactive values such as caches or helper objects.
Computed valuesValues derived from props, context, refs, or other computed values.
EventsThe inputs that request behavior from the machine.
GuardsBoolean rules that select whether a transition can run.
ActionsShort operations that update context, call callbacks, or send events.
EffectsWork that stays active while a state is active and can provide cleanup.
Connect APIThe framework-neutral view and control surface used by component code.

createMachine validates and returns this definition. The typed schema names the allowed states, events, context values, computed values, guards, actions, and effects. This keeps the machine contract and the component API aligned. References: packages/…/types.ts• L196-242, packages/…/create-machine.ts• L24-27, packages/…/toggle.types.ts• L23-37

State and transition model

States represent meaningful behavior modes rather than every value in the component. An event is looked up in the active state and its parent states, then the first transition whose guard passes is selected. A transition may keep the current state, move to another state, or run actions while staying in place.

Nested states express a parent behavior with a more specific child mode. Use a dotted state path for a nested value, such as open.idle. A parent can handle events for its active children. State tags provide stable facts such as open when callers should not depend on one exact state path. References: packages/…/state.ts• L33-70, packages/…/state.ts• L192-207, packages/…/state.ts• L241-248

Initial state

The initial-state function chooses the first state from normalized props. It is the place to map an initial or controlled input into the machine's behavior chart. For example, a dialog starts in open when open or defaultOpen is true; otherwise it starts in closed.

References: packages/…/types.ts• L209-212 packages/…/dialog.machine.ts• L28-31

State entry and exit

State entry and exit actions mark the boundaries of a state. State effects run for the lifetime of that state and are cleaned up when the state exits or the service stops. This lets a component keep focus control, outside-click tracking, or scroll locking tied to the behavior that needs it.

References: packages/…/types.ts• L177-194 packages/…/machine.ts• L242-281

Event contracts

Events are the internal language of a machine. Component interaction code sends events such as OPEN, CLOSE, or PRESS.TOGGLE; effects can send events when the DOM reports an outside click or another external change. Event payloads carry data needed by the selected action, such as a value for TRIGGER_VALUE.SET.

Use event names that state the intent and keep them stable within the component package. Public connect methods should send events instead of changing context directly. This keeps user calls, DOM interactions, and external effects on the same transition path. References: packages/…/dialog.types.ts• L146-150, packages/…/dialog.connect.ts• L18-27, packages/…/dialog.machine.ts• L147-155

Controlled and queued events

Controlled props are synchronized through explicit events. A prop watcher detects a change and sends a CONTROLLED.* event so the machine can reflect the external value without treating it as a user action. Public setters send the desired event even when the current state may not yet include an earlier queued event.

When a public setter represents the latest value, its event can use replaces with a shared key. The runtime then keeps only the newest queued event for that key. Use this only for public declarative setters; internal dismissal and timing events must remain separate so a user call cannot hide them.

References: packages/…/dialog.machine.ts• L51-55 packages/…/dialog.machine.ts• L62-74 packages/…/dialog.connect.ts• L18-22 packages/…/types.ts• L89-95

The following diagram shows the normal path from component input to rendered behavior.

flowchart LR
  P[Props or DOM input] --> C[connect API]
  C --> E[Event]
  E --> G{Guard selection}
  G -->|allowed| T[Transition]
  T --> A[Actions and context updates]
  T --> S[State change]
  S --> F[State effects]
  A --> O[Public callback or rendered output]
  F --> O

Context and props

Props describe what the component receives from its caller. Context describes reactive state that the machine owns or mirrors. A bindable context value supports an uncontrolled default, an optional controlled value, and an optional change callback. This gives component packages one state model for both usage styles.

Read context with context.get, update it with context.set, and read its starting value with context.initial. A context update can notify the caller through the bindable onChange function. Refs are different: they hold non-reactive data and do not represent rendered component state. References: packages/…/types.ts• L34-65, packages/…/toggle.machine.ts• L12-21

Props are normalized before the machine uses them. Defaults must allow caller values to override them. The normalized props also provide the machine scope, which gives framework-neutral access to instance IDs and DOM roots. References: packages/…/types.ts• L163-166, packages/…/dialog.machine.ts• L11-25, packages/…/types.ts• L78-87

Guards and actions

Guards answer whether a transition is allowed. They should inspect the current event, state, props, context, refs, or computed values and return a boolean. They do not perform state changes. When a transition has several guarded choices, the first matching choice wins; an unguarded choice acts as the fallback.

Actions perform the work selected by a transition. They can update context, call a prop callback, send another event, or use scope for a DOM-related task. Keep the transition decision in guards and the resulting change in actions so the behavior chart remains readable. References: packages/…/types.ts• L99-121, packages/…/machine.ts• L190-212, packages/…/machine.ts• L233-239

Computed values and watchers

Computed values expose derived facts without storing duplicate state in context. They are evaluated when requested and can combine props, context, refs, scope, and other computed values. Use them when a value should follow its inputs rather than become a second source of truth.

Watchers connect changes in props or context to actions. They are useful when external controlled input must enter the machine as an event or when a change needs a side effect. Track only the values that should trigger the response. References: packages/…/types.ts• L3-10, packages/…/types.ts• L27-32, packages/…/types.ts• L213-215, packages/…/dialog.machine.ts• L51-55

Effects and cleanup

Effects represent ongoing work tied to a state. They are the right boundary for subscriptions, DOM listeners, focus traps, scroll locks, and outside-interaction tracking. An effect may return a cleanup function; the runtime calls it when the state exits or the service stops.

An effect can return no cleanup when it has no resource to release. Any effect that adds a listener, observer, timer, or lock must return the matching cleanup. This prevents work from a former state from acting on a later state. References: packages/…/types.ts• L173-175, packages/…/machine.ts• L214-231, packages/…/dialog.machine.ts• L128-203

Connect API

The connect function is the public interaction contract for a component package. It receives a running machine service and a prop normalizer, then returns state values, imperative setters, and prop getters for the component's parts. Framework code uses this API instead of reading machine internals or sending events directly.

Prop getters combine part attributes, generated IDs, current state, accessibility attributes, and event handlers. The normalizer converts the common prop shape into the target framework's element shape. Public setters send named events, so they preserve the machine's guards, callbacks, and effects. References: plop/machine/src/{{machine}}.connect.ts.hbs#L1-L17, packages/…/prop-types.ts• L62-79, packages/…/dialog.connect.ts• L29-120

Service boundary

The service exposes the pieces that a connect function needs: current state, context, props, scope, computed access, refs, events, and send. The service is created by a framework adapter, but its shape stays common across adapters. This is what lets one machine serve React, Vue, Solid, Svelte, Preact, and vanilla consumers.

References: packages/…/types.ts• L269-285 packages/…/machine.ts• L37-40

Public API shape

The API type should describe what component consumers can observe and do. It should include semantic state values and setters, then prop getters for each supported component part. The toggle API illustrates a small contract; the dialog API illustrates a multi-part component with open state, trigger selection, and accessible element props.

References: packages/…/toggle.types.ts• L39-61 packages/…/dialog.types.ts• L167-192

Authoring flow

When a component package needs a machine, author the behavior and public interaction surface in this order:

  1. Define the schema for props, states, context, events, guards, actions, effects, and computed values.
  2. Normalize props and choose the initial state.
  3. Add bindable context for reactive state and refs for non-reactive helpers.
  4. Draw the states and events, then add guards for conditional paths.
  5. Add actions for state updates and callbacks. Add effects for work that must live with a state.
  6. Define the connect API with semantic values, public setters, and prop getters.
  7. Keep DOM queries in the component's DOM helper boundary and pass normalized props through the framework adapter.

This order separates the behavior contract from its rendering surface. It also makes the machine usable by more than one framework without changing its state model. References: plop/machine/src/{{machine}}.machine.ts.hbs#L1-L28, plop/machine/src/{{machine}}.types.ts.hbs#L1-L22, plop/machine/src/{{machine}}.connect.ts.hbs#L1-L17

Change checklist

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

  • Keep the schema unions in sync with every state, event, guard, action, effect, and computed key used by the machine.
  • When a controlled prop changes, preserve the matching CONTROLLED.* event path and callback behavior instead of updating context from the watcher.
  • When a public setter queues a replaceable event, use the same replaces key only for that setter's declarative value.
  • When a state effect adds a resource, keep its cleanup aligned with state exit and service stop behavior.
  • When a connect API adds a component part, keep its API type, anatomy part, DOM ID helper, and normalized prop getter aligned.

Important failure modes

TriggerConsequenceGuard
A controlled state change bypasses its machine eventThe visible state and change callback can follow different pathsRoute prop changes through a watcher and a CONTROLLED.* event
A public setter checks stale state before sendingRapid setter calls can drop the latest intended valueSend unconditionally and use replaces for the setter's queue slot
An effect does not clean up its listener or lockOld state behavior remains active after the component changes stateReturn cleanup from every resource-owning effect
A guarded transition has no matching fallbackAn event is ignored when no guard passesOrder guarded transitions deliberately and add an unguarded fallback when the event must act
A connect getter reads a stale snapshot or omits a part contractDOM attributes and event handlers do not match machine stateRead the service contract and keep API types and getters paired

Key files

FileWhy to read it
packages/…/types.tsDefines the shared contracts for machines, services, transitions, context, and effects.
packages/…/state.tsShows how state paths, nested states, tags, and transition lookup work.
packages/…/machine.tsShows the runtime boundary that evaluates guards, actions, effects, and queued events.
packages/…/dialog.machine.tsShows a complete state and interaction model with controlled state, effects, focus, and dismissal.
packages/…/dialog.connect.tsShows how a multi-part component exposes state, setters, accessibility props, and DOM handlers.
packages/…/dialog.types.tsShows how a component's props, schema, service, and public API are typed together.
packages/…/toggle.machine.tsShows the smallest useful controlled and uncontrolled context pattern.
packages/…/toggle.connect.tsShows the link from public DOM interaction to machine events.
plop/machine/src/{{machine}}.machine.ts.hbsProvides the standard starting shape for a new machine definition.
plop/machine/src/{{machine}}.connect.ts.hbsProvides the standard starting shape for a framework-neutral connect API.