← Lessons

quiz vs the machine

Gold1460

Frontend

The XState State Machines

Modeling UI logic as explicit finite states and guarded transitions.

6 min read · core · beat Gold to climb

What it is

XState lets you model logic as a finite state machine. Instead of scattered boolean flags, you declare the explicit states a feature can be in and the events that move between them.

Core pieces

  • States: named situations such as idle, loading, success, and failure.
  • Events: messages that may trigger a transition.
  • Transitions: rules mapping a state and event to the next state.
  • Guards: conditions that allow or block a transition.

Why explicit states help

With booleans you can reach impossible combinations like loading and error at once. A machine makes invalid states unrepresentable because you can only be in one defined state at a time. Actions can run on entry, on exit, or on a transition.

  • Transitions are deterministic.
  • Side effects attach to states or transitions.
  • Statecharts add nesting and parallel regions.

Key idea

XState models UI logic as explicit states and guarded transitions, making invalid combinations unrepresentable and behavior easy to reason about.

Check yourself

Answer to earn rating on the learn ladder.

1. What problem do explicit states solve over boolean flags?

2. What does a guard do in a transition?