State Machines with XState in Vue
useMachine() with XState v5, defining states and transitions, visualizing machine in devtools.
State Machines with XState in Vue is a free Vue Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Vue Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why State Machines?
Boolean flags like isLoading, isError, isSuccess can drift into impossible combinations. A state machine models a finite set of states and the allowed transitions between them, making invalid states unrepresentable.
Introducing XState
XState is a library for finite state machines and statecharts in JavaScript. The @xstate/vue package integrates it with Vue’s reactivity via a composable.
// terminal
// npm install xstate @xstate/vueDefining a Machine
createMachine describes states and transitions. Each state lists events under on that move to a target state.
import { createMachine } from "xstate"
const toggleMachine = createMachine({
id: "toggle",
initial: "inactive",
states: {
inactive: { on: { TOGGLE: "active" } },
active: { on: { TOGGLE: "inactive" } },
},
})States and Transitions
The machine starts in initial. Sending an event named under the current state’s on transitions to the named target. Events not listed are simply ignored — invalid transitions cannot happen.
A Fetch Machine
State machines shine for async flows. A fetch has clear states: idle, loading, success, failure — each with sensible transitions.
const fetchMachine = createMachine({
initial: "idle",
states: {
idle: { on: { FETCH: "loading" } },
loading: { on: { RESOLVE: "success", REJECT: "failure" } },
success: {},
failure: { on: { RETRY: "loading" } },
},
})useMachine in Vue
useMachine from @xstate/vue runs the machine inside a component and returns a reactive snapshot and a send function.
import { useMachine } from "@xstate/vue"
const { snapshot, send } = useMachine(fetchMachine)Reading the Current State
The reactive snapshot holds the current state. Check it with snapshot.value.matches("loading") — perfect for conditional rendering.
// template
// <Spinner v-if="snapshot.matches('loading')" />
// <Error v-if="snapshot.matches('failure')" />
console.log(snapshot.value.value) // "idle"Sending Events
Trigger transitions by calling send with an event. The machine moves to the next state only if the transition is defined for the current state.
function load() {
send({ type: "FETCH" })
}
// later, on resolve:
// send({ type: "RESOLVE" })Wiring Events in the Template
Bind UI actions to send. The state machine guarantees the button only advances the flow in valid ways.
<template>
<button @click="send({ type: 'FETCH' })">Load</button>
<button v-if="snapshot.matches('failure')" @click="send({ type: 'RETRY' })">
Retry
</button>
</template>Context for Extra Data
Machines can carry context — extended data like fetched results or error messages — updated by actions during transitions. The state stays finite while context holds the variable data.
createMachine({
context: { data: null, error: null },
initial: "idle",
states: { /* assign to context in transitions */ },
})Visualizing with Devtools
XState machines can be visualized as diagrams. The XState devtools / Stately inspector render the live machine, highlight the current state, and let you replay transitions — invaluable for understanding complex flows.
Quick Check
Check your understanding of XState in Vue.
Recap
You learned state machines with XState:
- State machines make invalid states impossible by defining finite states and allowed transitions.
createMachinedeclaresstateswithonevent-to-target transitions.useMachinefrom@xstate/vuereturns a reactivesnapshotandsend.- Read state with
snapshot.matches("..."); trigger transitions withsend({ type }). contextcarries extra data; XState devtools visualize the machine.
Frequently asked questions
Is the “State Machines with XState in Vue” lesson free?
Yes — the full text of “State Machines with XState in Vue” is free to read here on the web, and the Vue Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Vue Academy course, upgrade to CoddyKit PRO.
What will I learn in “State Machines with XState in Vue”?
useMachine() with XState v5, defining states and transitions, visualizing machine in devtools. You practise Vue Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Vue Academy?
No prior experience is required. Vue Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “State Machines with XState in Vue” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Vue Academy lesson?
Yes. Every Vue Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Advanced Reactivity: shallowRef and triggerRef
- Composable Factories and Parameterized Composables
- State Machines with XState in Vue
- effectScope for Grouped Effects