# useStateTransition > A React hook for state machines that guard transitions, not states. You list the allowed moves between states; the hook refuses the rest and reports them in `error`. A move can have a guard that decides which state to set. Works with React 17, 18, and 19. No runtime dependencies. MIT licence. Install with `npm install usestatetransition`. Import with `import { useStateTransition } from 'usestatetransition'`. The package ships ES module and CommonJS builds with TypeScript types. ## Usage ```tsx type Door = 'open' | 'closed' | 'locked'; const { state, dispatch, dispatchFn, error } = useStateTransition({ initial: 'closed', flows: [ { from: 'closed', to: ['open', 'locked'] }, { from: 'open', to: 'closed' }, { from: 'locked', to: 'closed', on: (to, setState, code) => { if (code === '1234') setState(to); } } ] }); dispatch('open'); // allowed: closed -> open dispatch('locked'); // from open: refused, error is "Undefined transition from open to locked" dispatch('closed', '1234'); // from locked: the guard receives '1234' as data ``` ## Rules - `options.initial` is the first state. `options.flows` lists the allowed transitions. - A flow has `from` (a state or array of states), `to` (a state or array of states), and an optional guard `on(requestedState, setState, data)`. - Without a guard, an allowed request moves to the requested state. With a guard, the hook calls it and the guard calls `setState` with any state, later or never. `setState` does not check the flows. - A request for the current state does nothing and clears `error`. - A request that no flow allows sets `error` and keeps the state. The next allowed request clears `error`. - The same `from` and `to` pair in two flows throws `Duplicate state transition from to ` during render. - The hook applies a request in an effect, so the new `state` appears on the next render. - `dispatch` keeps the same identity between renders. - `dispatchFn(map, data)` calls `map(currentState, data)`, which returns `{ to, data? }`. Use it when a callback might hold an old `state`. - Exported types: `BaseStateType`, `StateTransitionFlow`, `UseStateTransitionOptions`, `UseStateTransitionResult`, `Dispatch`, `DispatchFunction`, `DispatchMapFunction`. ## Docs - [Website with a live demo](https://sielay.github.io/useStateTransition/) - [README](https://github.com/sielay/useStateTransition#readme): full API reference - [Changelog](https://github.com/sielay/useStateTransition/blob/master/CHANGELOG.md) ## Optional - [Source code](https://github.com/sielay/useStateTransition) - [npm package](https://www.npmjs.com/package/usestatetransition) - [Support the author on Ko-fi](https://ko-fi.com/K3E32BRVZQ)