Skip to content

Nested/hierarchical States #21

@cassiozen

Description

@cassiozen

Nested states are beneficial for a myriad of reasons, including:

  • State nesting lets you define a new state rapidly in terms of an old one by reusing the behavior from the parent state
  • State nesting lets you get new behavior almost for free, reusing most of what is common from the parent states

Configuration

This is what a nested state machine configuration would look like:

// Traffic Lights
useStateMachine()({
  initial: "green",
  states: {
    green: {
      on: {
        TIMER: "yellow",
      },
    },
    yellow: {
      on: {
        TIMER: "red",
      },
    },
    red: {
      on: {
        TIMER: "green",
      },
      // Nested state: Pedestrian traffic light
      initial: "walk",
      states: {
        walk: {
          on: {
            PED_COUNTDOWN: "wait",
          },
        },
        wait: {
          on: {
            PED_COUNTDOWN: "stop",
          },
        },
        stop: {},
      },
    },
  },
});

State value representation:

The returned machine state would still have a string representation for the state value. Nested stated will be represented with dot syntax. For the above example, possible states are:

  • green
  • yellow
  • red.walk
  • red.wait
  • red.stop

Transitions & Effects

For every transition, the state machine should traverse the config three (depth-first) and find the shortest path for the transition.
Effects should be invoked on parent state only once: transitioning between child states should not re-fire parent effects.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions