Skip to content

Getting Started

Install the package using your preferred package manager:

Terminal window
npm install statecharts.sh
Terminal window
pnpm add statecharts.sh
Terminal window
bun add statecharts.sh

Create a simple toggle statechart:

import { chart } from "statecharts.sh";
const toggle = chart({
context: {},
initial: "inactive",
states: {
inactive: {
on: { TOGGLE: "active" },
},
active: {
on: { TOGGLE: "inactive" },
},
},
});

A chart is a blueprint. To run it, create an instance:

const instance = toggle.start();
console.log(instance.state.value); // "inactive"
instance.send("TOGGLE");
console.log(instance.state.value); // "active"

React to state transitions:

instance.subscribe((state) => {
console.log("Current state:", state.value);
});
instance.send("TOGGLE"); // logs: "Current state: inactive"

Store data alongside state:

const counter = chart({
context: { count: 0 },
initial: "idle",
states: {
idle: {
on: {
INCREMENT: {
actions: (ctx) => ({ count: ctx.count + 1 }),
},
DECREMENT: {
actions: (ctx) => ({ count: ctx.count - 1 }),
},
},
},
},
});
const instance = counter.start();
instance.send("INCREMENT");
console.log(instance.state.context.count); // 1