A minimal, type-safe state machine for React.
- Type-safe: Full TypeScript support for context and events.
- Minimal API: Fluent interface for defining states and transitions.
- Async Support: Native support for asynchronous handlers and transitions.
- React Hook:
useMachinehook for easy integration with React components. - Lifecycle Hooks:
onEnterandonExitfor managing side effects.
npm install @octavelaventure/onx
# or
yarn add @octavelaventure/onximport { ONX, useMachine } from 'onx';
// 1. Define your context
interface CounterContext {
count: number;
}
// 2. Create your machine
const counterMachine = new ONX<CounterContext>({ count: 0 })
.state('idle')
.on('INCREMENT', (context) => ({
context: { count: context.count + 1 }
}))
.on('DECREMENT', (context) => ({
context: { count: context.count - 1 }
}))
.start('idle');
// 3. Use it in your component
function Counter() {
const { count, send } = useMachine(counterMachine);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => send('INCREMENT')}>+</button>
<button onClick={() => send('DECREMENT')}>-</button>
</div>
);
}The main class for creating a state machine.
constructor(initialContext: TContext): Initialize with context..state(name: string, lifecycle?: { onExit?: ... }): Define a state..on(event: string, handler: StateHandler): Define an event handler for the current state..onEnter(handler: StateHandler): Define an entry handler for the current state..onExit(handler: (context) => void): Define an exit handler for the current state..start(initialState: string): Start the machine in a specific state.
React hook to consume the machine.
- Returns
{ state, context, send, machine }.
MIT