Every developer has written a component with five booleans — isLoading, isError, isOpen, isSaving, isDone — and then spent an afternoon debugging the combinations that should never happen. XState solves this by making you describe your component as a state machine: a list of states, and the events that move between them.
Here is a simple fetch machine:
import { createMachine } from "xstate"; const fetchMachine = createMachine({ id: "fetch", initial: "idle", states: { idle: { on: { FETCH: "loading" } }, loading: { on: { SUCCESS: "success", FAILURE: "error" }, }, success: { on: { FETCH: "loading" } }, error: { on: { RETRY: "loading" } }, }, }); The machine can only be in one state at a time, and it can only move along the transitions you wrote. There is no state where isLoading and isError are both true, because that combination simply does not exist.
In React, the @xstate/react package gives you a hook:
import { useMachine } from "@xstate/react"; const [state, send] = useMachine(fetchMachine); if (state.matches("loading")) return <p>Loading...</p>; Your UI becomes a direct reflection of the machine's state, and the logic is easy to test because it is just a machine, not a component.
XState is for you if you build multi-step flows — checkouts, wizards, uploads, forms with validation — where the number of possible states keeps growing. It is also great for teams, because a state diagram is something a designer and a developer can discuss together.
But know its limits. XState has a learning curve, and for a simple toggle or a single form it is overkill. The library is also bigger than a few lines of useState, so do not reach for it until your state actually has combinations worth modelling.
Start today: pick one component with three or more booleans, draw its states on paper, and rewrite it as a machine. If the drawing is hard, that is the machine telling you the UI was unclear.
