Skip to content

onLifecycle

onLifecycle<FC>(machine: FactoryMachine<FC>, config: StateHookConfig<FC>): () => void

Defined in: factory-machine-lifecycle.ts:86

Registers lifecycle hooks for a FactoryMachine, allowing fine-grained control over state transitions.

The configuration object is strictly keyed by entry state names (or ”*” for all states). For each state, you can specify:

  • enter: handler for entering the state
  • leave: handler for leaving the state
  • on: event configuration object

The on object is keyed by event names (or ”*” for all events). For each event, you can provide:

  • A direct entry handler (function) for the event (runs as effect)
  • Or an object with any event hook handler from the machine lifecycle:
    • before, after, effect, guard, handle, transition, resolveExit, update, notify, end, etc.

Note: Only enter and leave are valid at the state level. All other hooks must be specified inside on for events.

You can use ”*” for states and events to match all states or all events. For example:

onLifecycle(machine, {
"*": {
on: {
"*": {
after: (ev) => {
// Runs after any event, from any state
}
}
}
}
});
onLifecycle(machine, {
Idle: {
enter: (ev) => {}, // when entering Idle
leave: (ev) => {}, // when leaving Idle
on: {
start: {
before: (ev) => {}, // before start event
effect: (ev) => {}, // effect for start event
after: (ev) => {}, // after start event
// ...any other event hook from TransitionHookExtensions
},
tick: (ev) => {}, // direct effect handler for tick event
}
},
"*": {
enter: (ev) => {}, // runs for all states
leave: (ev) => {},
on: {
"*": { after: (ev) => {} }, // after any event
stop: (ev) => {}, // direct effect handler for stop event
}
}
});
Type Parameter
FC extends FactoryMachineContext<KeyedStateFactory>
ParameterTypeDescription
machineFactoryMachine<FC>The FactoryMachine instance to enhance.
configStateHookConfig<FC>Configuration object mapping states/events to hook functions.

Disposer function to remove all registered hooks.

(): void

void