Skip to content

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.

This example demonstrates the core concepts of state machines in Matchina:

  • Two simple states (On and Off) with no additional data
  • Direct transitions between states using string references
  • Using the addEventApi helper to create a clean API for transitions

Unlike the counter example which used a single state with data, this toggle example uses two distinct states to represent the On and Off conditions.

import { createMachine, defineStates, addEventApi } from "matchina";
export const createToggleMachine = () => {
const states = defineStates({
On: () => ({}),
Off: () => ({}),
});
// Create a machine with proper transitions
const machine = addEventApi(
createMachine(
states,
{
On: {
toggle: "Off",
turnOff: "Off",
},
Off: {
toggle: "On",
turnOn: "On",
},
},
states.Off() // Start in the Off state
)
);
return machine;
};
export type ToggleMachine = ReturnType<typeof createToggleMachine>;
  • The toggle uses direct state transitions (changing from one state to another)
  • The UI updates based on the current state
  • This pattern is useful for modeling components with distinct behavioral modes

Now that you’ve seen a basic toggle machine, you might want to explore: