Mermaid State Diagrams — Transitions, Guards, and Nested States
Build state machine diagrams with Mermaid. Learn state transitions, guards, nested (composite) states, forks, joins, and choice pseudostates for modeling behavior.
Detailed Explanation
What is a State Diagram?
A state diagram (also called a statechart) models the behavior of an entity that changes state in response to events. It is invaluable for modeling UI flows, order lifecycles, connection states, and any system with well-defined states and transitions.
Basic Syntax
States are defined by name, and transitions use --> with optional labels:
stateDiagram-v2
[*] --> Idle
Idle --> Processing : submit
Processing --> Success : complete
Processing --> Error : fail
Error --> Idle : retry
Success --> [*]
[*]represents the start and end pseudostates.- Transition labels after the colon describe the triggering event.
State Descriptions
Add descriptions to states using a colon:
stateDiagram-v2
state "Waiting for payment" as Pending
Pending : Entry / show payment form
Pending : Exit / hide form
Nested (Composite) States
States can contain sub-states to model complex behavior hierarchically:
stateDiagram-v2
[*] --> Active
state Active {
[*] --> Running
Running --> Paused : pause
Paused --> Running : resume
}
Active --> Terminated : kill
Terminated --> [*]
Fork and Join
Model concurrent (parallel) states with fork and join:
stateDiagram-v2
[*] --> fork_state
state fork_state <<fork>>
fork_state --> TaskA
fork_state --> TaskB
TaskA --> join_state
TaskB --> join_state
state join_state <<join>>
join_state --> Complete
Complete --> [*]
Choice Pseudostate
Use <<choice>> to model conditional branching based on guards:
stateDiagram-v2
[*] --> CheckAge
state CheckAge <<choice>>
CheckAge --> Adult : [age >= 18]
CheckAge --> Minor : [age < 18]
State diagrams in Mermaid support the stateDiagram-v2 syntax, which provides cleaner rendering and more features than the original stateDiagram syntax.
Use Case
A frontend engineer modeling the states of a multi-step checkout form. The state diagram captures Idle, Cart Review, Shipping Info, Payment, Processing, Confirmed, and Failed states — helping the team identify edge cases like payment timeout and retry logic.
Try It — Mermaid Diagram Editor
Related Topics
Mermaid Flowchart Basics — Syntax, Nodes, and Arrows
Diagram Types
Mermaid Class Diagrams for Object-Oriented Design
Diagram Types
Mermaid Sequence Diagrams — Participants, Messages, and Loops
Diagram Types
Mermaid Syntax Cheat Sheet — Quick Reference for All Diagram Types
Advanced
Mermaid Subgraphs — Grouping and Nested Diagrams
Advanced