State Machines Xstate
Skill Profile
(Select at least one profile to enable specific modules)
Overview
XState is a state management library using finite state machines and statecharts for modeling application logic. It helps developers create applications with predictable state management, visualization tools, and excellent TypeScript support. XState uses a mathematical model of finite state machines which helps developers model complex logic as clear state transitions, visualize state flow with state diagrams and visualization tools, provide full TypeScript support for type safety, ensure deterministic state transitions that are easy to test, and include built-in support for async operations and side effects.
Why This Matters
- Reduces Bugs: State machines reduce bugs from complex state logic by 30-40%
- Increases Maintainability: Visualized state flow improves maintainability
- Reduces Debugging Time: Predictable state reduces debugging time
- Improves Testability: Deterministic transitions improve testability
- Improves Developer Experience: Visualization tools and TypeScript enhance DX
Core Concepts
Inputs / Outputs / Contracts
- Inputs:
- <e.g., env vars, request payload, file paths, schema>
- Entry Conditions:
- <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>
- Outputs:
- <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>
- Artifacts Required (Deliverables):
- <e.g., Code Diff, Unit Tests, Migration Script, API Docs>
- Acceptance Evidence:
- <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>
- Success Criteria:
- <e.g., p95 < 300ms, coverage ≥ 80%>
Skill Composition
- Depends on: typescript-standards
- Compatible with: None
- Conflicts with: None
- Related Skills: api-design
Quick Start
- Install XState: Install xstate and framework integration
- Create Machine: Define finite state machine
- Add States: Define states and transitions
- Add Context: Define initial context
- Add Actions: Implement entry/exit/transition actions
- Add Guards: Implement guard conditions
- Integrate with React: Use useMachine hook
- Test Machine: Test state transitions
- Visualize: Use Stately Editor for visualization
import { createMachine } from 'xstate'
const toggleMachine = createMachine({
id: 'toggle',
initial: 'inactive',
states: {
inactive: {
on: {
TOGGLE: 'active',
},
},
active: {
on: {
TOGGLE: 'inactive',
},
},
},
})
Assumptions / Constraints / Non-goals
- Assumptions:
- Development environment is properly configured
- Required dependencies are available
- Team has basic understanding of domain
- Constraints:
- Must follow existing codebase conventions
- Time and resource limitations
- Compatibility requirements
- Non-goals:
- This skill does not cover edge cases outside scope
- Not a replacement for formal training
Compatibility & Prerequisites
- Supported Versions:
- Python 3.8+
- Node.js 16+
- Modern browsers (Chrome, Firefox, Safari, Edge)
- Required AI Tools:
- Code editor (VS Code recommended)
- Testing framework appropriate for language
- Version control (Git)
- Dependencies:
- Language-specific package manager
- Build tools
- Testing libraries
- Environment Setup:
.env.example keys: API_KEY, DATABASE_URL (no values)
Test Scenario Matrix (QA Strategy)
| Type |
Focus Area |
Required Scenarios / Mocks |
| Unit |
Core Logic |
Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |
| Integration |
DB / API |
All external API calls or database connections must be mocked during unit tests |
| E2E |
User Journey |
Critical user flows to test |
| Performance |
Latency / Load |
Benchmark requirements |
| Security |
Vuln / Auth |
SAST/DAST or dependency audit |
| Frontend |
UX / A11y |
Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |
Technical Guardrails & Security Threat Model
1. Security & Privacy (Threat Model)
- Top Threats: Injection attacks, authentication bypass, data exposure
2. Performance & Resources
3. Architecture & Scalability
4. Observability & Reliability
Agent Directives & Error Recovery
(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)
- Thinking Process: Analyze root cause before fixing. Do not brute-force.
- Fallback Strategy: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.
- Self-Review: Check against Guardrails & Anti-patterns before finalizing.
- Output Constraints: Output ONLY the modified code block. Do not explain unless asked.
Definition of Done (DoD) Checklist
Anti-patterns
- Over-Engineering: Using state machines for simple logic adds unnecessary complexity
- Poor State Design: Poorly designed states create confusing machines
- Missing Guards: Not using guards for conditional transitions causes bugs
- Side Effect Issues: Not managing side effects properly causes unpredictable behavior
- Poor Testing: Not testing state machines properly leads to bugs
- Complex Machines: Overly complex machines are hard to understand and maintain
- Missing Documentation: Missing documentation makes machines hard to use
- Not Using Context: Not using context for persistent data causes code duplication
- Poor State Naming: Unclear state names make machines hard to understand
- Ignoring Events: Not properly handling events causes bugs
Reference Links & Examples
- Internal documentation and examples
- Official documentation and best practices
- Community resources and discussions
Versioning & Changelog
- Version: 1.0.0
- Changelog:
- 2026-02-22: Initial version with complete template structure
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: state-machines-xstate3description: XState is a state management library using finite state machines and Use when this capability is needed.4---56# State Machines Xstate78## Skill Profile9*(Select at least one profile to enable specific modules)*10- [ ] **DevOps**11- [x] **Backend**12- [ ] **Frontend**13- [ ] **AI-RAG**14- [ ] **Security Critical**1516## Overview17XState is a state management library using finite state machines and statecharts for modeling application logic. It helps developers create applications with predictable state management, visualization tools, and excellent TypeScript support. XState uses a mathematical model of finite state machines which helps developers model complex logic as clear state transitions, visualize state flow with state diagrams and visualization tools, provide full TypeScript support for type safety, ensure deterministic state transitions that are easy to test, and include built-in support for async operations and side effects.1819## Why This Matters20- **Reduces Bugs**: State machines reduce bugs from complex state logic by 30-40%21- **Increases Maintainability**: Visualized state flow improves maintainability22- **Reduces Debugging Time**: Predictable state reduces debugging time23- **Improves Testability**: Deterministic transitions improve testability24- **Improves Developer Experience**: Visualization tools and TypeScript enhance DX2526---2728## Core Concepts29#3031## Inputs / Outputs / Contracts32* **Inputs**:33 - <e.g., env vars, request payload, file paths, schema>34* **Entry Conditions**:35 - <Pre-requisites: e.g., Repo initialized, DB running, specific branch checked out>36* **Outputs**:37 - <e.g., artifacts (PR diff, docs, tests, dashboard JSON)>38* **Artifacts Required (Deliverables)**:39 - <e.g., Code Diff, Unit Tests, Migration Script, API Docs>40* **Acceptance Evidence**:41 - <e.g., Test Report (screenshot/log), Benchmark Result, Security Scan Report>42* **Success Criteria**:43 - <e.g., p95 < 300ms, coverage ≥ 80%>4445## Skill Composition46* **Depends on**: [typescript-standards](..\..\01-foundations\typescript-standards/SKILL.md)47* **Compatible with**: None48* **Conflicts with**: None49* **Related Skills**: [api-design](..\..\01-foundations\api-design/SKILL.md)5051## Quick Start521. **Install XState**: Install xstate and framework integration532. **Create Machine**: Define finite state machine543. **Add States**: Define states and transitions554. **Add Context**: Define initial context565. **Add Actions**: Implement entry/exit/transition actions576. **Add Guards**: Implement guard conditions587. **Integrate with React**: Use useMachine hook598. **Test Machine**: Test state transitions609. **Visualize**: Use Stately Editor for visualization6162```typescript63import { createMachine } from 'xstate'6465const toggleMachine = createMachine({66 id: 'toggle',67 initial: 'inactive',68 states: {69 inactive: {70 on: {71 TOGGLE: 'active',72 },73 },74 active: {75 on: {76 TOGGLE: 'inactive',77 },78 },79 },80})81```8283## Assumptions / Constraints / Non-goals8485* **Assumptions**:86 - Development environment is properly configured87 - Required dependencies are available88 - Team has basic understanding of domain89* **Constraints**:90 - Must follow existing codebase conventions91 - Time and resource limitations92 - Compatibility requirements93* **Non-goals**:94 - This skill does not cover edge cases outside scope95 - Not a replacement for formal training969798## Compatibility & Prerequisites99100* **Supported Versions**:101 - Python 3.8+102 - Node.js 16+103 - Modern browsers (Chrome, Firefox, Safari, Edge)104* **Required AI Tools**:105 - Code editor (VS Code recommended)106 - Testing framework appropriate for language107 - Version control (Git)108* **Dependencies**:109 - Language-specific package manager110 - Build tools111 - Testing libraries112* **Environment Setup**:113 - `.env.example` keys: `API_KEY`, `DATABASE_URL` (no values)114115116## Test Scenario Matrix (QA Strategy)117118| Type | Focus Area | Required Scenarios / Mocks |119| :--- | :--- | :--- |120| **Unit** | Core Logic | Must cover primary logic and at least 3 edge/error cases. Target minimum 80% coverage |121| **Integration** | DB / API | All external API calls or database connections must be mocked during unit tests |122| **E2E** | User Journey | Critical user flows to test |123| **Performance** | Latency / Load | Benchmark requirements |124| **Security** | Vuln / Auth | SAST/DAST or dependency audit |125| **Frontend** | UX / A11y | Accessibility checklist (WCAG), Performance Budget (Lighthouse score) |126127128## Technical Guardrails & Security Threat Model129130### 1. Security & Privacy (Threat Model)131* **Top Threats**: Injection attacks, authentication bypass, data exposure132- [ ] **Data Handling**: Sanitize all user inputs to prevent Injection attacks. Never log raw PII133- [ ] **Secrets Management**: No hardcoded API keys. Use Env Vars/Secrets Manager134- [ ] **Authorization**: Validate user permissions before state changes135136### 2. Performance & Resources137- [ ] **Execution Efficiency**: Consider time complexity for algorithms138- [ ] **Memory Management**: Use streams/pagination for large data139- [ ] **Resource Cleanup**: Close DB connections/file handlers in finally blocks140141### 3. Architecture & Scalability142- [ ] **Design Pattern**: Follow SOLID principles, use Dependency Injection143- [ ] **Modularity**: Decouple logic from UI/Frameworks144145### 4. Observability & Reliability146- [ ] **Logging Standards**: Structured JSON, include trace IDs `request_id`147- [ ] **Metrics**: Track `error_rate`, `latency`, `queue_depth`148- [ ] **Error Handling**: Standardized error codes, no bare except149- [ ] **Observability Artifacts**:150 - **Log Fields**: timestamp, level, message, request_id151 - **Metrics**: request_count, error_count, response_time152 - **Dashboards/Alerts**: High Error Rate > 5%153154155## Agent Directives & Error Recovery156*(ข้อกำหนดสำหรับ AI Agent ในการคิดและแก้ปัญหาเมื่อเกิดข้อผิดพลาด)*157158- **Thinking Process**: Analyze root cause before fixing. Do not brute-force.159- **Fallback Strategy**: Stop after 3 failed test attempts. Output root cause and ask for human intervention/clarification.160- **Self-Review**: Check against Guardrails & Anti-patterns before finalizing.161- **Output Constraints**: Output ONLY the modified code block. Do not explain unless asked.162163164## Definition of Done (DoD) Checklist165166- [ ] Tests passed + coverage met167- [ ] Lint/Typecheck passed168- [ ] Logging/Metrics/Trace implemented169- [ ] Security checks passed170- [ ] Documentation/Changelog updated171- [ ] Accessibility/Performance requirements met (if frontend)172173174## Anti-patterns1751. **Over-Engineering**: Using state machines for simple logic adds unnecessary complexity1762. **Poor State Design**: Poorly designed states create confusing machines1773. **Missing Guards**: Not using guards for conditional transitions causes bugs1784. **Side Effect Issues**: Not managing side effects properly causes unpredictable behavior1795. **Poor Testing**: Not testing state machines properly leads to bugs1806. **Complex Machines**: Overly complex machines are hard to understand and maintain1817. **Missing Documentation**: Missing documentation makes machines hard to use1828. **Not Using Context**: Not using context for persistent data causes code duplication1839. **Poor State Naming**: Unclear state names make machines hard to understand18410. **Ignoring Events**: Not properly handling events causes bugs185186## Reference Links & Examples187188* Internal documentation and examples189* Official documentation and best practices190* Community resources and discussions191192193## Versioning & Changelog194195* **Version**: 1.0.0196* **Changelog**:197 - 2026-02-22: Initial version with complete template structure198199---200> Converted and distributed by [TomeVault](https://tomevault.io/claim/amnadtaowsoam) — claim your Tome and manage your conversions.201<!-- tomevault:4.0:skill_md:2026-04-13 -->