React Integration
This example builds a multi-step checkout flow with machina and React 19. The FSM in fsm.ts imports only machina, and the machina-react hooks do the subscription work. machina-react is built on React’s useSyncExternalStore, and snapshots stay consistent under concurrent rendering.
What It Demonstrates
Section titled “What It Demonstrates”machina concepts:
createFsmwith a typed context object that the FSM and the React layer share by reference_onEnterlifecycle hooks for side effects, like the async payment simulation and flag clearing- Payload arguments through
handle("next", formData), where components own ephemeral form state and submit it on transition canHandle()for computing each button’s disabled state
machina-react integration:
CheckoutProviderstores the FSM in ordinary React context, the provider pattern from the machina-react README- The provider creates the FSM once in a ref, which avoids the StrictMode double-invoke problem around disposal
useCheckout()wrapsuseFsm(fsm)and returns{ state, context, handle, canHandle }to componentsuseCheckoutSelector()wrapsuseFsmSelectorfor components that need a derived slice
The Integration Layer
Section titled “The Integration Layer”The full React wiring is 49 lines in src/hooks/useCheckout.tsx. Trimmed to the exported pieces:
Components call useCheckout() and read state and context from the snapshot. useFsm subscribes through useSyncExternalStore and rerenders the component when the FSM settles after an input.
Design Notes
Section titled “Design Notes”Context is shared by reference. createCheckoutFsm() returns { fsm, context }, and the FSM mutates that one object on each handle() call. The machina-react snapshot exposes the same live reference, and components read current values whenever a settled snapshot triggers a render.
The provider skips useEffect cleanup for the FSM. React StrictMode simulates unmount and remount for effects without re-running the component body. A cleanup that disposed the FSM would leave the remounted tree subscribed to a disposed instance before the ref could recreate it. Disposal is unnecessary here: the FSM’s state is in-memory only, and garbage collection reclaims it when the provider unmounts.
startOver resets context fields in place. The hook layer and the components read one shared object. Replacing it with a fresh object would break the shared reference, and components would still read the old one. Resetting the fields in place preserves the reference.