Nested and Hierarchical States
You'll learn: How to organize complex FSM behavior by nesting child states inside parent states, inheriting transitions and actions from the hierarchy.
Why Hierarchical States?
Real-world behavior often isn't flat. Imagine a media player: it has playing, paused, and stopped states. But within playing, you might have substates like buffering or streaming. Rather than duplicate transitions (like "pause" or "stop") for every substate, you can define them once on the parent state and let children inherit them.
The Core Idea
A nested state is a state within another state. The outer state is the parent or superstate, and the inner ones are children or substates. When an event occurs:
- Check if the current substate handles it
- If not, bubble up to the parent state
- The parent's transitions and actions apply to all children unless overridden
This creates a hierarchy that reduces duplication and models real-world relationships naturally.
Conceptual Example
const mediaPlayer = {
idle: {},
playing: {
// Parent state
substates: {
buffering: {},
streaming: {}
},
on: {
PAUSE: 'paused', // Applies to buffering AND streaming
STOP: 'idle'
}
},
paused: {}
};
// From playing.buffering, PAUSE transitions to paused
// From playing.streaming, PAUSE also transitions to paused
// No need to repeat the PAUSE handler in each substate
The playing state's transitions are inherited by buffering and streaming. You model complexity once at the appropriate level.
Key Takeaway:
Nested states let you build hierarchies where child states inherit transitions and actions from parents, reducing redundancy and modeling complex behavior more naturally.