Quick Start
Installation
Section titled “Installation”npm install matchina
Interactive Example: Traffic Light
Section titled “Interactive Example: Traffic Light”Here’s a simple traffic light state machine that demonstrates Matchina’s core concepts:
Source Code
Section titled “Source Code”import { defineStates, matchina } from "matchina";
const states = defineStates({ Red: () => ({ message: "Stop" }), Yellow: () => ({ message: "Prepare to stop" }), Green: () => ({ message: "Go" }),});
export const createTrafficLightMachine = () => { return matchina( states, { Red: { next: "Green" }, Yellow: { next: "Red" }, Green: { next: "Yellow" }, }, "Red" );};
export type TrafficLightMachine = ReturnType<typeof createTrafficLightMachine>;
import { useMachine } from "matchina/react";import { type TrafficLightMachine } from "./machine";
export const TrafficLightView = ({ machine,}: { machine: TrafficLightMachine;}) => { useMachine(machine); const currentState = machine.getState(); const stateMessage = currentState.data.message; return ( <div className="flex flex-col items-center"> <div className="bg-gray-800 p-4 rounded-lg mb-4"> <div className="flex flex-row space-x-4 items-center"> {/* Red light */} <div className={`w-16 h-16 rounded-full ${ currentState.is("Red") ? "bg-red-600" : "bg-red-900" }`} /> {/* Yellow light */} <div className={`w-16 h-16 rounded-full ${ currentState.is("Yellow") ? "bg-yellow-400" : "bg-yellow-900" }`} /> {/* Green light */} <div className={`w-16 h-16 rounded-full ${ currentState.is("Green") ? "bg-green-500" : "bg-green-900" }`} /> </div> </div>
<div className="text-xl font-bold mb-4">{stateMessage}</div>
<div className="text-sm mb-4"> Current state: <span className="font-mono">{currentState.key}</span> </div>
<button className="px-4 py-2 rounded bg-blue-500 text-white hover:bg-blue-600" onClick={() => machine.next()} > Next Signal </button> </div> );};
import { useMemo } from "react";import { TrafficLightView } from "./TrafficLightView";import { createTrafficLightMachine } from "./machine";
export function TrafficLightDemo() { const machine = useMemo(createTrafficLightMachine, []); return <TrafficLightView machine={machine} />;}
For a detailed walkthrough and explanation, see the Traffic Light Example.
Key Concepts Demonstrated
Section titled “Key Concepts Demonstrated”- State Definition: Define states with typed data using
defineStates()
- Machine Creation: Create a state machine with
matchina()
by specifying states, transitions, and initial state - Transition Definition: Define allowed state transitions as a simple object structure
- React Integration: Integrate state machines in React components with
useMachine()
Next Steps
Section titled “Next Steps”- State Machines - Learn how to build more complex state machines
- Matchbox Factories - Understand type-safe state handling
- React Integration - Integrate state machines with React components
- Browse Examples - Explore practical examples