Skip to content

    Frontend System Design

    Statecharts and Hierarchical State

    How statecharts extend state machines with parallel regions, history states and final states, and what each costs, with a pure TypeScript model and tests.

    By Published 13 min read

    • frontend-system-design
    • state-management
    • statecharts
    • state-machines
    Share

    Standard lessonadvancedTypeScript labFrontend System Design

    Before this: Finite State Machines for UI

    What you'll learn: By the end of this lesson you will be able to explain what a statechart adds to a flat state machine, use parallel regions so that independent concerns stop multiplying each other's states, choose between shallow and deep history to bring a user back to where they were, use final states and done events to finish a flow when all of its parts are finished, and say when these features earn their cost.

    Think of a car dashboard. The ignition can be off, on or running. Separately, the indicator lamp is off, left or right, and the radio is off or playing. Nobody draws one huge diagram with a box for "running, left indicator, radio playing". The three things are independent, and each has its own small diagram. Now think of the glovebox: when you close it and open it again, it does not reorganise itself, it still holds what you left in it. That is memory of where you were.

    A statechart is a state machine with those two ideas, and a few others, added. This lesson covers the ones that matter in a user interface: nesting, parallel regions, history and final states. The lab is a small model written for this lesson. It is not XState and it is not a complete SCXML engine.

    The core idea

    1. A flat state machine multiplies states when concerns are independent. Three on/off switches need eight states if they must be one machine.
    2. Statecharts add structure, not new power. Stately's documentation says statecharts add hierarchy, concurrency and communication to ordinary state machines. This lesson uses the first two, plus history and final states.
    3. Each addition is a rule you must be able to test: which regions receive an event, what a history state remembers, and when a parent is "done".

    Three illustrations run through the lesson: a minimal example (a text toolbar with three independent regions), a realistic example (a checkout whose payment panel remembers where the shopper was) and a failure or edge example (history that restores more or less than you expected).

    State Machines With XState already covers parent states, guards and the order of exit, transition and entry actions. This lesson assumes it and goes into what it left out. The plain, flat machine comes first in the course in the lesson on finite state machines for UI.

    Where a statechart sits

    A statechart is still a pure function from a state and an event to a new state. The component sends events and renders the state value; the chart decides.

    Figure 1. The statechart is a pure core between events and rendering

    A statechart sits between the events a component sends and the state value it rendersComponent to Chart (event); Chart to State (new state); State to Component (state value); State to Effects runner (effects to run)Component: sends events, rendersComponentsends events,rendersChart: pure transition functionChartpure transitionfunctionState: active states and historyStateactive states andhistoryEffects runner: network, timersEffects runnernetwork, timerseventnew statestate valueeffects to run

    How to read this: the chart never touches the network or the DOM. It returns the next state, which includes the active states and the memory of any history states, and the caller performs effects.

    Hierarchy in one paragraph

    A parent (compound) state contains child states and names an initial child. An event goes to the deepest active state first and then up through its parents, so one rule on the parent covers every child. A transition leaves the states below the common ancestor of its source and target, deepest first, and then enters the target path outer to inner. SCXML states the same order for one transition: the source states are exited, the transition's actions run, and the target states are entered. The rest of this lesson builds on that.

    Parallel regions: independent concerns, one state each

    A parallel state has children, called regions, that are all active at once. Stately's documentation says the state value of a parallel state is an object holding the value of each region, and that an event received in a parallel state is received and handled by all of its regions. SCXML says it as "when a parallel element is active, all of its children are active".

    Minimal example: a text toolbar. Bold is on or off, italic is on or off, and the list style is none, bullets or numbers. Written as regions, you draw 2 + 2 + 3 = 7 small states. Written flat, you would need one state for every combination, 2 x 2 x 3 = 12, and every event would need a rule in every one of them. The lab prints both counts.

    Figure 2. Three regions of the toolbar

    stateDiagram-v2 accTitle: Toolbar with three parallel regions accDescr: A toolbar state has three regions that are active at the same time. The bold region toggles between off and on. The italic region toggles between off and on. The list region moves between none, bullets and numbers. A CLEAR event is handled by each region that is not already in its first state. state Toolbar { [*] --> BoldOff BoldOff --> BoldOn: TOGGLE_BOLD BoldOn --> BoldOff: TOGGLE_BOLD or CLEAR -- [*] --> ItalicOff ItalicOff --> ItalicOn: TOGGLE_ITALIC ItalicOn --> ItalicOff: TOGGLE_ITALIC or CLEAR -- [*] --> ListNone ListNone --> Bullets: BULLETS ListNone --> Numbers: NUMBERS Bullets --> ListNone: BULLETS or CLEAR Numbers --> ListNone: NUMBERS or CLEAR }

    How to read this: the dashed lines split the regions. At any moment the toolbar is in one state of each region, so its full state is a triple such as bold on, italic off, list bullets.

    Stately's page on transitions adds the rule for events: when several regions each have an enabled transition, all of them are taken, and regions with none stay where they are. The lab's CLEAR event shows it. In the captured trace below, CLEAR is one event, and all three regions answer it.

    Expected output, captured from a real run (Node 26.13.1; sections 1 and 2):

    === 1. Regions: states you write versus configurations you get
    editor toolbar: 7 leaf states written, 12 configurations reachable
    flat equivalent: 12 states, one for each combination
    settings dialog: 7 leaf states written, 10 configurations (alternatives add, regions multiply)
    
    === 2. Toolbar: each event reaches every region, and CLEAR is answered by all three
    start          {"bold":"off","italic":"off","list":"none"}
    TOGGLE_BOLD    {"bold":"on","italic":"off","list":"none"}
                   entered [bold.on]  exited [bold.off]
    BULLETS        {"bold":"on","italic":"off","list":"bullets"}
                   entered [list.bullets]  exited [list.none]
    TOGGLE_ITALIC  {"bold":"on","italic":"on","list":"bullets"}
                   entered [italic.on]  exited [italic.off]
    NUMBERS        {"bold":"on","italic":"on","list":"numbers"}
                   entered [list.numbers]  exited [list.bullets]
    CLEAR          {"bold":"off","italic":"off","list":"none"}
                   entered [bold.off, italic.off, list.none]  exited [bold.on, italic.on, list.numbers]
    CLEAR          {"bold":"off","italic":"off","list":"none"}
                   ignored

    Two things to notice. The count is a product over regions and a sum over alternatives, which is why the settings dialog with 7 written states has 10 configurations. And a second CLEAR, when nothing is on, is ignored: no region has a rule for it.

    Regions are not threads: the model handles one event at a time, to completion, and "parallel" means "active together". The cost: regions are independent only if they are. Once the list style must change when bold is switched on, the regions need to talk, and they are no longer the clean product you drew.

    History: coming back to where you were

    A history state is a pseudostate: you never stay in it. Stately says it remembers the last child state that was active before its parent was exited, and entering it restores that. There are two kinds. A shallow history state remembers the immediate child; a deep history state remembers the deepest active state or states inside its children. SCXML words it the same way: shallow remembers which immediate child was active, deep saves the full active descendant configuration, down to the atomic states.

    Realistic example: a checkout with a payment panel. The shopper is at the card form, on the second field. They tap "edit address", fix a typo and go back. The chart has a payment parent with a card child, which has the fields number and cvc, and a paypal child. Without history, "back" enters payment and lands on its initial state, the first field. With history, it lands where they were.

    Figure 3. A payment panel with two ways back

    stateDiagram-v2 accTitle: Checkout payment panel and the address screen accDescr: The shopper starts in the cart and pays, entering the payment panel at the card number field. Inside the panel, next moves from the card number to the cvc field, and choosing PayPal moves to the PayPal child. Edit address leaves the panel for the address screen. From the address screen, a shallow history return restores the card child at its first field, and a deep history return restores the card cvc field exactly. [*] --> Cart Cart --> Payment: PAY state Payment { [*] --> Card state Card { [*] --> Number Number --> Cvc: NEXT } Card --> PayPal: USE_PAYPAL } Payment --> Address: EDIT_ADDRESS Address --> Payment: BACK_SHALLOW (child only) Address --> Payment: BACK_DEEP (exact place) Payment --> Paid: DONE

    How to read this: both returns target the payment panel. They differ in what is restored: the child that was active, or the whole configuration below it.

    The next captured trace uses the lab's checkout. Read the pairs of lines after each BACK_... event.

    Expected output, captured from a real run (Node 26.13.1; section 3, first part):

    === 3. Checkout: shallow and deep history after leaving the payment panel
    start          "cart"
    PAY            {"payment":{"card":"number"}}
                   entered [payment, payment.card, payment.card.number]  exited [cart]
    NEXT           {"payment":{"card":"cvc"}}
                   entered [payment.card.cvc]  exited [payment.card.number]
    EDIT_ADDRESS   "address"
                   entered [address]  exited [payment.card.cvc, payment.card, payment]
    BACK_SHALLOW   {"payment":{"card":"number"}}
                   entered [payment, payment.card, payment.card.number]  exited [address]
    NEXT           {"payment":{"card":"cvc"}}
                   entered [payment.card.cvc]  exited [payment.card.number]
    EDIT_ADDRESS   "address"
                   entered [address]  exited [payment.card.cvc, payment.card, payment]
    BACK_DEEP      {"payment":{"card":"cvc"}}
                   entered [payment, payment.card, payment.card.cvc]  exited [address]

    Shallow history remembered card but entered it the normal way, so the shopper is back at number. Deep history restored card.cvc. Shallow suits a child whose own start is a sensible place to resume; deep suits cases where the exact place matters.

    What if nothing was remembered? Stately says that if no child state was remembered, a history state goes to its target when one is given, and otherwise to the parent's initial state. SCXML requires that a processor behave as if the default transition had been taken. The lab shows both cases.

    Expected output, captured from a real run (Node 26.13.1; sections 4a and 4b):

    === 4a. Checkout: a shallow history that was never recorded uses its target
    start          "cart"
    ADDRESS        "address"
                   entered [address]  exited [cart]
    BACK_SHALLOW   {"payment":"paypal"}
                   entered [payment, payment.paypal]  exited [address]
    
    === 4b. Checkout: a deep history that was never recorded uses the parent's initial state
    start          "cart"
    ADDRESS        "address"
                   entered [address]  exited [cart]
    BACK_DEEP      {"payment":{"card":"number"}}
                   entered [payment, payment.card, payment.card.number]  exited [address]

    With no memory, the shallow history went to its target, PayPal, and the deep history went to the parent's initial child, the card form at its first field.

    Final states and done events

    A final state marks completion. Stately says that when a child final state is reached, its parent is done and the parent's onDone transition is taken, and that a parallel state is done once all of its regions are done. SCXML says a processor must generate the event done.state.id after a final state is entered, where id is the parent's id.

    This is how a screen with two jobs finishes by itself. The lab's settings dialog has an avatar upload and a details save in two regions, each ending in a finished final state, and onDone on the parallel state closes the dialog.

    Figure 4. How two finished regions close the dialog

    sequenceDiagram accTitle: Done events closing a settings dialog accDescr: The details region receives SAVED and enters its final state, which raises done for the details region. The avatar region is still uploading, so the dialog stays open. Later UPLOADED arrives and the avatar region enters its final state, raising done for the avatar region. Every region is now done, so the dialog raises its own done event, and its onDone rule moves the chart to closed. All of this happens inside the single call that handled UPLOADED. participant UI as Component participant C as Chart UI->>C: SAVED Note over C: details enters final, raises done.dialog.details Note over C: avatar not done, dialog stays open UI->>C: UPLOADED Note over C: avatar enters final, raises done.dialog.avatar Note over C: every region done, raises done.dialog C->>C: onDone, leave dialog, enter closed C-->>UI: closed

    How to read this: a done event is internal. It is raised by the chart itself and handled before the call returns, so the component never sees a half-finished state.

    That last point is the run-to-completion idea. SCXML calls one transition set a microstep and a series of microsteps that ends with an empty internal event queue a macrostep, and it places a generated event at the rear of the internal queue. The lab does the same: internal events are processed before send returns.

    Expected output, captured from a real run (Node 26.13.1; section 5):

    === 5. Settings dialog: a parallel state is done only when every region is done
    start          {"dialog":{"avatar":"choosing","details":"editing"}}
    UPLOAD         {"dialog":{"avatar":"uploading","details":"editing"}}
                   entered [dialog.avatar.uploading]  exited [dialog.avatar.choosing]
    SAVE           {"dialog":{"avatar":"uploading","details":"saving"}}
                   entered [dialog.details.saving]  exited [dialog.details.editing]
    SAVED          {"dialog":{"avatar":"uploading","details":"finished"}}
                   entered [dialog.details.finished]  exited [dialog.details.saving]  raised [done.dialog.details]
    UPLOAD_FAILED  {"dialog":{"avatar":"choosing","details":"finished"}}
                   entered [dialog.avatar.choosing]  exited [dialog.avatar.uploading]
    UPLOAD         {"dialog":{"avatar":"uploading","details":"finished"}}
                   entered [dialog.avatar.uploading]  exited [dialog.avatar.choosing]
    UPLOADED       "closed"
                   entered [dialog.avatar.finished, closed]  exited [dialog.avatar.uploading, dialog.details.finished, dialog.details, dialog.avatar.finished, dialog.avatar, dialog]  raised [done.dialog.avatar, done.dialog]

    After SAVED the details region is done but the dialog stays open. A failed upload sends the avatar region back to choosing, and the dialog only closes when UPLOADED makes both regions final.

    Choosing

    Figure 5. Which statechart feature do you need?

    flowchart TD accTitle: Choosing a statechart feature accDescr: If one rule should cover several states, use nested states. If two concerns are independent and would multiply each other's states, use parallel regions. If the user must return to where they were after leaving a parent, use history, shallow if the child's start is a fine place and deep if the exact place matters. If a flow must end when several parts are done, use final states and a done rule. If none of these applies, a flat machine is enough. Q{"What is awkward in the flat machine?"} -->|"the same rule repeated in many states"| H["Nested states"] Q -->|"independent concerns multiply the states"| P["Parallel regions"] Q -->|"leaving and coming back loses the place"| M{"Resume where?"} M -->|"the child's own start is fine"| S["Shallow history"] M -->|"the exact place matters"| D["Deep history"] Q -->|"a flow ends when several parts finish"| F["Final states and a done rule"] Q -->|"nothing"| X["Keep the flat machine"]

    How to read this: start from the pain, not from the feature. Each feature answers one pain.

    Feature Gain Cost
    Nested states One rule covers many states A transition now has a "domain" to reason about
    Parallel regions Independent concerns stay small Regions that must talk are no longer independent
    Shallow history Resume at the child The child restarts from its own initial state
    Deep history Resume exactly Stale memory can restore a state that no longer makes sense
    Final states and done A flow finishes itself Done events are implicit, so trace them

    Build it: parallel regions, history and done events

    Goal. Run the lab's three charts, read the entered, exited and raised lists, and change one rule to see a test fail.

    Setup. The lab is in the course's example workspace (Node 26.13.1, pnpm). It is pure logic: no React, no DOM, no timers and no state machine library. It is a new lab that extends the idea of the statechart-model lab used in the XState lesson.

    cd examples/frontend
    pnpm install
    cd labs/parallel-history-statecharts
    pnpm test           # 24 tests
    node src/demo.ts

    Steps.

    1. Run the tests, then the demo.
    2. In section 2, find the CLEAR event: three states entered and three exited by one event.
    3. In section 3, compare the two BACK_ lines and say which kind of history each used.
    4. In section 5, find the line where raised is empty on the UPLOAD_FAILED event and explain why the dialog did not close.

    What the lab does not show. It has no guards, actions, context, delays, always-transitions or invoked actors. Where two regions pick conflicting transitions, SCXML prefers the transition in the descendant and otherwise the one chosen by the earlier state in document order; the lab simply skips a transition whose source has already been left, which is a simplification. It was never compared with the xstate package.

    Break it. In src/chart.ts, in step, change (child.history ?? "shallow") === "deep" to (child.history ?? "shallow") === "shallow". Deep and shallow swap meaning and three tests fail. Put it back.

    In practice: the payment panel that forgot the shopper

    NOTE

    This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every number in it is an illustrative assumption.

    The situation

    The checkout has a payment panel and an address screen. Shoppers who go back to fix an address lose their place in the card form, and support sees an increase (illustrative) in abandoned carts at that step.

    Starting architecture

    Figure 6. Starting point: the panel keeps its place in component state

    Starting architecture: the panel keeps its field position in component state that unmounts with itAddress screen to Checkout chart (BACK); Checkout chart to Payment panel (enter panel)Address screen: edit and go backAddress screenedit and go backPayment panel: local field positionPayment panellocal fieldpositionCheckout chart: no memory of the panelCheckout chartno memory of thepanelBACKenter panel

    How to read this: the panel unmounts when the shopper leaves, so its local position is gone. The chart enters the panel from its initial state every time.

    Options considered

    Option What it fixes What it costs Risk
    Lift the field position into global state Survives unmount A second place that must agree with the chart Two sources of truth
    Shallow history on the panel Returns to the card form The form restarts at its first field Not exact
    Deep history on the panel Returns to the exact field Memory must be cleared when it goes stale Stale restores

    The decision

    Field Decision record
    Context The panel loses the shopper's place whenever they leave it.
    Decision Add a deep history state to the payment panel and send the shopper back through it. Clear it when the session or the card token expires.
    Consequences, good One mechanism in the chart, testable as a table of events.
    Consequences, bad The memory is part of the state and must be reset on purpose.
    Revisit when The panel gains parallel regions, whose memory is bigger.

    Rollout and verification

    1. Write the history tests first: leave from each field and return.
    2. Add the memory reset as an event and test that a return after it enters the initial state.
    3. Release behind a flag and compare completion of the payment step.

    The 2 a.m. failure

    A shopper returns from the address screen to a cvc field, but the card number was cleared when the payment session timed out. The field has nothing to go with it and the shopper is stuck (illustrative). First three checks: (1) read the state's memory for the history state; (2) see whether any event clears it; (3) see what else expired at the same time. Mitigation: send the reset event on timeout so the return enters the first field. Follow-up: make every history state's reset rule part of its tests. Exercise 3 asks for this.

    Architect's notes

    • Draw the regions before you code them, and ask for each pair whether one ever needs to know the other's state.
    • Pick shallow history by default, and deep only when the exact place matters.
    • Treat history memory as state: it is saved, restored, reset and tested like any other value.
    • Trace done events: the chart raises them for you, so show them in logs.

    Common mistakes

    • Using regions for things that depend on each other, which only hides the coupling.
    • Expecting deep history from a shallow history state.
    • Forgetting the default: a history state entered before its parent was ever left must still go somewhere.
    • Targeting a state inside a parallel state from outside, which re-enters every region in the lab's model.

    Key takeaways

    • A statechart adds structure to a state machine: hierarchy, parallel regions, history and final states.
    • Parallel regions are all active at once, and the state value is one entry per region.
    • History restores the last child (shallow) or the whole configuration (deep), and falls back to its target or the parent's initial state.
    • A final state makes its parent done; a parallel state is done when all of its regions are.
    • Done events are internal and run to completion before the call returns.

    Practice exercises

    Exercise 1 — Starter (45 min): Draw a media player as two regions, playback (paused, playing) and volume (normal, muted). Count the flat states and the states in the regions, and check the numbers with configurationCount.

    Exercise 2 — Intermediate (2 hours): Add a help screen to the lab's checkout that is entered from anywhere inside payment and leaves through a deep history state. Write the table test for leaving from card.number, card.cvc and paypal.

    Exercise 3 — Advanced (half day): Add a RESET_MEMORY event that clears the stored memory of a history state. Write the test that reproduces the stale-restore failure first, then make it pass.

    In this course:

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments