@yantrix/react v0.2.1 • Docs
Yantrix API / @yantrix/react / useFSM
Function: useFSM()
ts
function useFSM(Automata): TUseFsmReturnuseFSM
React hook that initializes and subscribes to a Yantrix FSM instance.
Behavior:
- Lazily creates or reuses a singleton FSM instance keyed by its id.
- Subscribes the component to FSM updates by tracking the machine "version" (currentCycle) via useSyncExternalStore, ensuring a re-render on every transition.
- Exposes imperative helpers: dispatch, getContext, getInstanceAutomata, trace, and automata statics.
Contract:
- This base hook does not accept a selector. For derived reads, use useFSMWithSelector(...).
- trace() is side-effect free: it stores the last action and previous context in refs to avoid extra renders.
Parameters
• Automata: TAutomataConstructorWithStatic | TUseFSMProps
Either:
- a generated Automata class (constructor with static helpers) or
- a props object { Automata, id } produced by codegen to create a distinct instance per id.
Returns
TUseFsmReturn An object with:
- state: current numeric state
- getContext(): current state+context
- dispatch(action): dispatches an action payload
- trace():
- getInstanceAutomata(): underlying IAutomata
- getAutomatasList(): registry map of id -> instance
- automata static helpers spread in (e.g., getState, getAction, statesDictionary, actionsDictionary)
Example
ts
const { getContext, dispatch, getState } = useFSM(TrafficLight);
const onClick = () => dispatch({ action: TrafficLight.getAction('Switch'), payload: {} });
const { state, context } = getContext();
const isRed = state === getState('Red');