Vibe Coding

How to Use State Machine Diagrams for AI Coding with Claude

Get Claude to map out every state and transition before it writes (or rewrites) your code.

Trần Quang Hùng
Trần Quang HùngChief Explainer of Things
January 11, 20268 min read
Share:
State machine diagram overlaid on code editor showing states and transitions for a UI component

QUICK INFO

Difficulty Beginner
Time Required 15-20 minutes
Prerequisites Basic understanding of components (React, Vue, or similar)
Tools Needed Claude (claude.ai or API), any code editor

What You'll Learn:

  • What state machine diagrams are and why they matter for AI-assisted coding
  • How to prompt Claude to generate diagrams from existing components
  • How to use those diagrams to catch missing edge cases before they become bugs

A state machine diagram is a visual map of how something moves between different conditions. For a dropdown menu, that means showing when it's closed, open, loading, or errored, and what causes each transition. When you ask Claude to generate these diagrams before or during coding, it forces the model to think through every path your component might take.

This matters because AI coding assistants tend to handle the happy path well but miss edge cases. A login form might work perfectly when credentials are correct, then break when the network times out mid-request. The diagram surfaces those gaps.

What State Machine Diagrams Actually Are

A state machine has three parts: states (the conditions something can be in), transitions (what causes movement between states), and the initial state (where things start).

For a toggle button, the states are just "on" and "off." The transition is a click event. For a shopping cart, you might have empty, has items, checking out, processing payment, order complete, and payment failed. Each arrow between boxes represents a user action or system event.

The notation isn't rigid. You can use formal UML state diagrams, Mermaid syntax (which Claude handles well), or just boxes and arrows in plain text. What matters is that every possible state appears somewhere on the diagram, and every transition has a trigger.

Here's Mermaid syntax for a simple modal:

stateDiagram-v2
    [*] --> Closed
    Closed --> Open: user clicks trigger
    Open --> Closed: user clicks outside
    Open --> Closed: user presses Escape
    Open --> Closed: user clicks close button

That's it. Four states if you count the initial state, four transitions. The diagram forces you to answer: what happens if the user presses Escape while the modal is animating open? Claude might not think to handle that unless the diagram prompts the question.

Why This Works for AI Coding

Andrej Karpathy popularized "vibe coding" on Twitter, describing a style where you describe what you want to an AI and let it generate the implementation. The approach works surprisingly well for straightforward features, but struggles with complex state.

The issue is that language models default to the most common patterns in their training data. If most login forms in the training set don't handle session expiry mid-submission, Claude won't think to add that case unless prompted. State diagrams are a structured way to do that prompting.

There's another benefit: verification. When Claude produces a diagram of your existing component, you can eyeball it in seconds and spot missing transitions. Reading through 200 lines of reducer logic takes longer and you're more likely to miss things.

Getting Claude to Generate Diagrams

Start with an existing component. Paste the code and ask: "Create a state machine diagram of this component showing all possible states and transitions."

Claude typically responds with Mermaid syntax. If you want a different format, specify it. "Show me a plain text state diagram with ASCII arrows" works fine.

Example prompt for an existing component:

Here's my checkout form component. Create a state machine diagram 
showing every state this component can be in and what causes transitions 
between them. Use Mermaid syntax.

[paste your component code]

Expected output: Claude returns a stateDiagram-v2 block listing states like idle, validating, submitting, success, and error, with labeled transitions between them.

The diagram might be incomplete. That's the point. If Claude's diagram is missing a loading state you know exists in the code, that's a mismatch worth investigating. If the diagram shows a transition that doesn't exist in your implementation, you've found a gap.

For new components

When building something from scratch, describe the feature first, then ask for the diagram before any implementation:

I'm building a file upload component with drag-and-drop support. 
Before writing any code, create a state machine diagram showing 
all the states and transitions this component should handle.

Review the diagram. Add states Claude missed ("what about when the file type is invalid?"). Then tell Claude to implement the component following the diagram exactly.

Reading and Verifying Diagrams

Look for three things when reviewing a Claude-generated diagram:

Dead ends: States with no outgoing transitions (other than terminal states like "success"). If your error state has no way back to the form, users are stuck.

Missing triggers: Check that every user action and system event appears as a transition label. If "network timeout" doesn't show up anywhere, Claude probably isn't handling it.

Impossible paths: Sometimes Claude imagines transitions that can't actually happen. A transition from "submitting" directly to "idle" might skip cleanup logic you need.

When you find issues, tell Claude directly: "Add a transition from error back to idle when user clicks retry. Also add a timeout transition from submitting to error."

A Quick Example

Say you have a dropdown that fetches options from an API. You might start with:

Create a state machine diagram for an async dropdown component 
that loads options from an API when opened.

Claude might produce:

stateDiagram-v2
    [*] --> Closed
    Closed --> Loading: user opens dropdown
    Loading --> Open: options loaded
    Loading --> Error: fetch failed
    Open --> Closed: user selects option
    Open --> Closed: user clicks outside
    Error --> Loading: user retries
    Error --> Closed: user dismisses

Now you can ask: what if the user closes the dropdown while it's still loading? What if they open it again before the first request completes? Add those cases to the diagram, then ask Claude to implement with race condition handling.

When This Isn't Worth It

Simple components with one or two states don't need diagrams. A button that toggles a boolean isn't going to surprise you. Use this technique for anything with async operations, multiple user inputs, or error states.

I haven't tested this extensively with other AI coding tools. Copilot's inline suggestions work differently enough that the workflow probably doesn't transfer directly. Cursor might handle it similarly to Claude since it can use Claude as a backend, but I'm not sure.

Troubleshooting

Claude's diagram doesn't match the code: This usually means the code has implicit states Claude didn't recognize. A component that sets isLoading = true and isError = false at the same time is in a distinct state even without a named constant. Point this out and ask for an updated diagram.

Mermaid syntax errors: Claude occasionally produces invalid Mermaid. The most common issue is unescaped special characters in transition labels. Ask Claude to fix the syntax or just manually correct it. The diagram content matters more than perfect rendering.

Too many states: Complex components can have dozens of states. Ask Claude to group related states or focus on a specific flow: "Just diagram the checkout payment flow, not the entire cart lifecycle."


PROMPT TEMPLATES

Diagram an Existing Component

Create a state machine diagram of this component showing all possible 
states and what triggers transitions between them. Use Mermaid stateDiagram-v2 
syntax. Include error states and loading states if applicable.

[paste component code]

Customize by: Add specific states you want Claude to look for: "Make sure to include the case where validation fails."

Design Before Implementation

I'm building [describe feature]. Before writing code, create a state 
machine diagram showing every state and transition this feature needs 
to handle. Include edge cases like network failures and user cancellation.

Example output:

stateDiagram-v2
    [*] --> Idle
    Idle --> Validating: user submits
    Validating --> Submitting: validation passes
    Validating --> Idle: validation fails
    Submitting --> Success: server accepts
    Submitting --> Error: server rejects
    Submitting --> Error: network timeout
    Error --> Idle: user edits form
    Success --> [*]

FAQ

Q: Does Claude actually write better code after generating a diagram? A: In my experience, yes, but not dramatically. The main value is catching issues earlier. Claude doesn't magically handle every edge case; you still need to review the diagram and point out gaps.

Q: Can I use this with TypeScript state machine libraries like XState? A: Yes. Ask Claude to generate XState machine configs instead of Mermaid diagrams. The output is directly usable code.

Q: What if my component doesn't fit a state machine model? A: Some components are better modeled as data transformations than state machines. If your component just maps props to rendered output with no internal state, skip this technique.


RESOURCES

Tags:state machine diagramsclaude aivibe codingreact componentsui developmentdebuggingstate management
Trần Quang Hùng

Trần Quang Hùng

Chief Explainer of Things

Hùng is the guy his friends text when their Wi-Fi breaks, their code won't compile, or their furniture instructions make no sense. Now he's channeling that energy into guides that help thousands of readers solve problems without the panic.

Related Articles

Stay Ahead of the AI Curve

Get the latest AI news, reviews, and deals delivered straight to your inbox. Join 100,000+ AI enthusiasts.

By subscribing, you agree to our Privacy Policy. Unsubscribe anytime.

How to Use State Machine Diagrams for AI Coding with Claude | aiHola