useStateTransition

State machines that guard transitions

useStateTransition is a React hook. You list the moves that are allowed between states, and the hook refuses the rest. A move can have a guard that decides what happens next.

npm install usestatetransition

Transitions, not states

Declare which moves are allowed. Any other move keeps the state and reports an error.

Guards with data

A guard receives the data you send and picks the next state, now, later, or never.

Small

No runtime dependencies. Types, ES module, and CommonJS builds. React 17, 18, and 19.

Try it

This door runs on the hook. You can open, close, and lock it. Unlocking needs the code 1234. Try a move that is not allowed, such as locking an open door.

The demo needs JavaScript.

The code behind the demo

import { useStateTransition } from 'usestatetransition';

type Door = 'open' | 'closed' | 'locked';

const { state, dispatch, error } = useStateTransition<Door>({
  initial: 'closed',
  flows: [
    { from: 'closed', to: ['open', 'locked'] },
    { from: 'open', to: 'closed' },
    {
      from: 'locked',
      to: 'closed',
      // A guard: unlock only with the right code.
      on: (to, setState, code) => {
        if (code === '1234') setState(to);
      }
    }
  ]
});

dispatch('open');
dispatch('closed', code); // the guard receives the code as data

Install

npm install usestatetransition

React is a peer dependency, so the hook uses your app's copy of React 17, 18, or 19. The package needs Node.js 18 or later for server rendering and tests.

API

const { state, dispatch, dispatchFn, error } = useStateTransition<StateType>({ initial, flows });
Name What it does
initial The first state. States are strings, numbers, or an enum.
flows The allowed transitions. Each flow has from and to, each a state or a list of states, and an optional guard on(requestedState, setState, data).
state The current state.
dispatch(state, data?) Requests a transition. A flow without a guard moves to the state. A flow with a guard calls it, and the guard calls setState. A request that no flow allows sets error.
dispatchFn(map, data?) Requests a transition that depends on the current state. map(currentState, data) returns { to, data? }.
error The error from the latest request, or undefined.

The README on GitHub has the full reference. For AI agents, read llms.txt.

Free, and kept up to date

The hook is free and MIT licensed. If it saves you time, a coffee helps me keep it working with each new React.

Support me on Ko-fi