Skip to content

React Quick Start

Install the library:

Terminal window
npm install statecharts.sh

The useStateChart hook connects a statechart to your component:

import { chart } from "statecharts.sh";
import { useStateChart } from "statecharts.sh/react";
const toggle = chart({
context: {},
initial: "inactive",
states: {
inactive: { on: { TOGGLE: "active" } },
active: { on: { TOGGLE: "inactive" } },
},
});
function Toggle() {
const { state, send, matches } = useStateChart(toggle);
return (
<button onClick={() => send("TOGGLE")}>
{matches("active") ? "ON" : "OFF"}
</button>
);
}

The hook returns:

PropertyTypeDescription
stateIStateSnapshotCurrent state with value and context
send(event) => voidSend events to the machine
matches(stateValue) => booleanCheck current state