Skip to content

Repository files navigation

ONX

A minimal, type-safe state machine for React.

Features

  • 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: useMachine hook for easy integration with React components.
  • Lifecycle Hooks: onEnter and onExit for managing side effects.

Installation

npm install @octavelaventure/onx
# or
yarn add @octavelaventure/onx

Usage

import { 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>
  );
}

API

ONX<TContext>

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.

useMachine(machine: ONX<TContext>)

React hook to consume the machine.

  • Returns { state, context, send, machine }.

License

MIT

About

A minimal, type-safe state machine for React.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages