What it is
onx is a small state machine library for React. States, events and transitions are declared with a fluent API, the context and events are fully typed, and a single hook connects a machine to a component.
Highlights
- Typed context and events, checked by the compiler.
- A fluent API: declare a state, then the events it handles.
- Async handlers and transitions out of the box.
onEnterandonExitlifecycle hooks for side effects.useMachinereturns the current state, the context andsend.- No runtime dependencies besides React.
Example
import { ONX, useMachine } from "@octavelaventure/onx";
const counter = new ONX<{ count: number }>({ count: 0 })
.state("idle")
.on("INCREMENT", (ctx) => ({ context: { count: ctx.count + 1 } }))
.on("DECREMENT", (ctx) => ({ context: { count: ctx.count - 1 } }))
.start("idle");
function Counter() {
const { context, send } = useMachine(counter);
return <button onClick={() => send("INCREMENT")}>{context.count}</button>;
}
Install
npm install @octavelaventure/onx