Toggle State Machine
A simple toggle state machine that switches between On and Off states, demonstrating the most basic state machine pattern with two states and direct transitions between them.
Implementation details
Section titled “Implementation details”Two distinct states (On and Off) with no additional data. Direct transitions between states using string references. The addEventApi helper creates a clean event-dispatch API.
Unlike the counter example which uses a single state with data, toggle uses two distinct states to represent the On and Off conditions.
import { createMachine, defineStates, addEventApi } from "matchina";
export const createToggleMachine = () => { const states = defineStates({ On: undefined, Off: undefined, });
// Create a machine with proper transitions const machine = addEventApi( createMachine( states, { On: { toggle: "Off", turnOff: "Off", }, Off: { toggle: "On", turnOn: "On", }, }, "Off" // Start in the Off state ) );
return machine;};
export type ToggleMachine = ReturnType<typeof createToggleMachine>;Next steps
Section titled “Next steps”- Counter Example — add numeric data to your states
- Traffic Light Example — create a machine with more states
- Lifecycle Hooks — add behavior when states change