Hierarchical Statecharts & UI Actor Model
Flat Finite State Machines suffer combinatorial explosion when independent UI modes multiply (e.g., 4 upload phases times 3 network modes = 12 duplicated states). Hierarchical statecharts nest child states, run orthogonal regions in parallel, and isolate async work inside spawned actors that cancel automatically on state exit.
Hierarchical Statechart Exit & Actor Teardown
Trace how a parent-level ABORT event bubbles from a child state and tears down an active async actor.
Machine sits in 'editing.payment' while a spawned 'stripeIntent' actor polls payment status.
state: { editing: 'payment' }, actors: ['stripeIntent']- activePath
- checkout.editing.payment
- actorStatus
- running
Under the Hood
W3C SCXML evaluates transitions from the deepest active leaf state upward to the root. If a parent state handles an event (such as CANCEL), every active child state exits cleanly in reverse entry order before the parent transitions.
- Compound states: Group shared transitions (
RESET,ABORT) on a parent node so child states (validating,submitting) inherit them without duplication. - Orthogonal regions: Execute independent state machines side by side (e.g.,
playback: playing | pausedalongsidecaptions: on | off) without Cartesian product states. - Actor isolation: Spawn child actors with their own mailbox and AbortController so exiting a parent state terminates in-flight sockets deterministically.
const wizardChart = {
id: 'checkout',
initial: 'editing',
states: {
editing: {
initial: 'shipping',
states: { shipping: { on: { NEXT: 'payment' } }, payment: {} },
on: { ABORT: 'cancelled' } // inherited by shipping & payment
},
cancelled: { type: 'final' }
}
};Problem Genealogy
- 1987 (Harel Statecharts): Introduced depth (AND/OR states) and history pseudo-states to collapse flat FSMs that grew exponentially with each feature.
- 2014 (W3C SCXML): Standardized deterministic event-queue microsteps, exit/entry action ordering, and parallel
<parallel>regions. - 2020+ (UI Actor Runtimes): Paired hierarchical charts with message-passing actors so each async fetch or WebSocket owns an isolated lifecycle.
Production Pitfalls
- Orphaned async callbacks after parent exit: Spawning a raw
fetch()inside a transition without binding its lifetime to the state node writes stale responses after the user leaves the wizard. - Infinite microstep loops: Transient (
always) transitions that update context and re-enter the same guard freeze the main thread in a synchronous loop.
- When not to use hierarchical statecharts: For linear 2-step forms or single-resource fetch lifecycles, a flat discriminated union avoids ~12–30 KB of statechart interpreter runtime and indirection.