Skip to content

Quick Start

Let’s create a traffic light button like this:

Loading...

Full Code

35 lines, 822 chars
export const trafficLight = matchina(
  {
    Red: () => "means stop",
    Yellow: () => "means caution",
    Green: () => "means go",
  },
  {
    Red: { next: "Green" },
    Yellow: { next: "Red" },
    Green: { next: "Yellow" },
  },
  'Red'
);

export const TrafficLight = () => {
  useMachine(trafficLight.machine);
  const { state } = trafficLight
  return (
    <button title="Click to Change"
      className={`rounded ${trafficLight.state.match({
        Red: () => "bg-red-500",
        Yellow: () => "bg-yellow-500",
        Green: () => "bg-green-500",
      })}`} 
      onClick={() => trafficLight.next()}
    >
      {state.key} {state.data}
    </button>
  );
}

Step by Step:

Define States

const states = defineStates({
  Red: () => "means stop",
  Yellow: () => "means caution",
  Green: () => "means go",
})

Define Transitions

const transitions = {
  Red: { next: "Green" },
  Yellow: { next: "Red" },
  Green: { next: "Yellow" },
}

Create Machine with Initial State

const machine = createFactoryMachine(
  states, 
  transitions, 
  "Red"
)

Use Machine (React)

export const TrafficLight = () => {
  useMachine(trafficLight.machine);
  return (
   ...
  );
}

match cases

trafficLight.state.match({
  Red: () => "bg-red-500",
  Yellow: () => "bg-yellow-500",
  Green: () => "bg-green-500",
})

Send machine events

trafficLight.next()