Mermaid state diagram syntax: stateDiagram-v2 and examples

Writing in Markdown6 min read

To draw a state machine in Markdown, put stateDiagram-v2 on the first line of a mermaid fenced code block, connect states with -->, and mark the start and end points with [*]. Always write stateDiagram-v2 rather than stateDiagram, because the unversioned keyword still routes to Mermaid's legacy renderer with cramped spacing and weaker support for nested states. State diagrams fit lifecycles where one object moves between named modes on specific events, whereas step-by-step procedures belong in a Mermaid flowchart. Every diagram below opens in the Mermaid live editor, and the other diagram types are summarized in Mermaid in Markdown.

The smallest state diagram and why v2 matters

```mermaid
stateDiagram-v2
    [*] --> Draft
    Draft --> Review : submit
    Review --> Draft : request changes
    Review --> Published : approve
    Published --> [*]
```
The state diagram this code draws
Open in the Mermaid editor

Each line declares a transition between two state identifiers. A single-word state comes into existence on first use without prior declaration. The [*] token draws both the solid initial circle and the ringed final circle; Mermaid picks the symbol from whether [*] sits on the left or right of -->.

Dropping -v2 is the most common mistake when copying older snippets. Mermaid kept stateDiagram for backward compatibility, while stateDiagram-v2 uses the modern layout engine, cleaner font metrics, direction overrides, and proper routing around composite states. Start every new block with stateDiagram-v2.

Naming states, aliases, and transition guards

Bare identifiers work for single words like Idle or Closed. Once a state name contains spaces, punctuation, or non-ASCII text, declare it with state "Label" as id and reference the short id in transitions:

state "Waiting for payment" as awaiting_payment
state "Paid in full" as paid
awaiting_payment --> paid : webhook [amount == total]

Mermaid also accepts id : Label to describe a state, though state "Label" as id is easier to scan because it never looks like an arrow label. Text after a colon on a --> line sits on the arrow itself. In UML statecharts, that label conventionally combines an event trigger with an optional guard condition in square brackets, such as retry [attempts < 3]. Mermaid treats everything after : as plain text, so square brackets need no escaping.

Composite states, choices, forks, and concurrent regions

A lifecycle earns a state diagram over a flowchart once several sub-states share one outer transition, such as cancelling an order from any step inside payment processing. Wrap sub-states in curly braces after state Name:

```mermaid
stateDiagram-v2
    direction LR
    [*] --> Idle
    Idle --> Processing : start

    state Processing {
        [*] --> Validating
        Validating --> CheckResult : check
        state CheckResult <<choice>>
        CheckResult --> Charging : valid
        CheckResult --> Failed : invalid
        Charging --> [*]
    }

    Processing --> Completed : settled
    Processing --> Cancelled : cancel
    Failed --> Idle : edit
    Completed --> [*]
    Cancelled --> [*]
```
The state diagram this code draws
Open in the Mermaid editor

Inside Processing, the inner [*] marks which sub-state runs first, and transitions attached to Processing apply to the entire group rather than repeating cancel arrows from every inner node.

Stereotypes in double angle brackets turn a state identifier into a UML pseudo-state:

Stereotype Drawn as When to use it
<<choice>> Diamond One incoming transition branches into mutually exclusive paths by condition
<<fork>> Thick bar One incoming transition splits into parallel states that run simultaneously
<<join>> Thick bar Parallel states finish before a single outgoing transition continues

Mermaid 11.14.0 also accepts [[choice]], [[fork]], and [[join]], though <<...>> matches standard UML notation. Here is how <<fork>> and <<join>> pair up when two background tasks must both finish:

```mermaid
stateDiagram-v2
    state split_work <<fork>>
    state merge_work <<join>>

    [*] --> split_work
    split_work --> UploadAssets
    split_work --> BuildIndex
    UploadAssets --> merge_work
    BuildIndex --> merge_work
    merge_work --> Ready : all tasks done
    Ready --> [*]
```
The state diagram this code draws
Open in the Mermaid editor

When two independent state machines run side by side inside one active mode, such as playback status alongside network connectivity, separate them inside a composite state with -- on its own line:

```mermaid
stateDiagram-v2
    [*] --> Active
    state Active {
        [*] --> Playing
        Playing --> Paused : toggle
        Paused --> Playing : toggle
        --
        [*] --> Online
        Online --> Offline : connection lost
        Offline --> Online : reconnected
    }
    note right of Active
        Playback and connectivity
        change independently.
    end note
```
The state diagram this code draws
Open in the Mermaid editor

Write exactly two hyphens (--), never three (---). Three hyphens act as Markdown's horizontal rule and slide separator, and Mermaid's state lexer rejects them.

Direction, notes, and styling

State diagrams flow top to bottom (TB) by default. Adding direction LR switches the layout to left-to-right, and BT or RL reverse those axes. You can also place direction inside a composite state to orient its sub-states independently when arrows do not cross the group boundary.

Attach callouts with note right of StateId or note left of StateId. A one-line note uses a colon (note left of Idle : Waiting for input), while a multi-line note omits the colon and closes with end note. For restrained emphasis, classDef errorState fill:#fde8e8,stroke:#c53030 and Failed:::errorState highlight exception states; keep custom fills subtle so both light and dark modes stay readable.

How rendering works in MiaoYan

In MiaoYan on Mac, iPhone, and iPad, the Markdown parser emits a <code class="language-mermaid"> block, and the preview hands its text to the bundled mermaid.min.js (Mermaid 11.14.0). Rendering runs locally inside the WebView with zero network requests, keeping internal architecture private and working offline. Rendered SVGs are cached per diagram and appearance theme. When modeling request-response messages across multiple services rather than one entity's modes, a Mermaid sequence diagram is usually clearer.

Common syntax traps and how to check

MiaoYan leaves unparseable Mermaid blocks as raw code rather than injecting error banners that would leak into PDF exports. Check these five traps first:

%% Broken examples to avoid:
Draft -->|submit| Review
state Waiting for review
Active : Entry: start timer
---
  1. Flowchart pipe labels (-->|submit|). Pipes belong to flowchart. Use a trailing colon instead: Draft --> Review : submit.
  2. Unquoted spaces in state IDs. Alias multi-word names first: state "Waiting for review" as waiting.
  3. Extra colons in unquoted text. Stray colons split tokens early; quote labels inside state "..." as id.
  4. Three hyphens (---) instead of --. Concurrent regions require --.
  5. Undeclared <<choice>> nodes. Declare state checkName <<choice>> so Mermaid draws a diamond instead of a named box.

On Mac, type /mermaid and press Tab to insert a starter fence, then press ⌘\ for split view or ⌘3 for preview. Paste tricky blocks into the Mermaid live editor to read exact parser line numbers. MiaoYan is on the App Store for Mac, iPhone, and iPad, with source code on GitHub.

FAQ

Should I ever use stateDiagram instead of stateDiagram-v2?

No for new notes. stateDiagram invokes Mermaid's legacy renderer, which lacks direction control and struggles with nested composite states and concurrent regions.

Why does [*] mark both the start and the end?

Mermaid follows PlantUML notation: [*] on the left of --> draws the solid initial dot, and [*] on the right draws the ringed terminal dot. Each composite state can include its own inner [*] pair.

When should I pick stateDiagram-v2 over flowchart?

Use stateDiagram-v2 for the lifecycle of one object, such as an order, connection, or background job, where valid states and transitions matter. Use flowchart for procedures and multi-service pipelines.

Do state diagrams work offline on iPhone and iPad?

Yes. MiaoYan bundles Mermaid 11.14.0 across Mac, iPhone, and iPad, rendering stateDiagram-v2 offline in previews as well as PDF, HTML, and image exports.