Course contentsShow
← React
Lesson 1751 of 2,39641. State Management EcosystemFree lesson

XState Core Concepts: States, Events, Transitions

Understanding the fundamental building blocks: finite states, events that trigger transitions, and transition definitions.

XState Core Concepts: States, Events, Transitions

What you'll learn: The three fundamental building blocks of state machines—states, events, and transitions—and how they create predictable state management.

The Building Blocks Analogy

Think of a traffic light. It has finite states (red, yellow, green), events that trigger changes (timer expires, emergency vehicle approaches), and transitions (the rules that determine which state comes next).

XState formalizes this pattern for your application state.

States: The Finite Set of Possibilities

A state machine defines all possible states your feature can be in. Unlike ad-hoc state where you might have isLoading, hasError, and data all simultaneously (creating impossible combinations), a state machine says: "You're either idle, loading, success, or error—never two at once."

// Explicit, mutually exclusive states
const states = {
  idle: {},
  loading: {},
  success: {},
  error: {}
}

Events: The Triggers

Events are the only way to change states. They're named actions that happen: FETCH, RETRY, CANCEL. Events are explicit and traceable—you can't mysteriously end up in a different state.

// Events are plain objects with a type
{ type: 'FETCH' }
{ type: 'ERROR', message: 'Network failed' }

Transitions: The Rules

Transitions define which events cause which state changes. They're like a map: "When in idle state, the FETCH event transitions to loading." Invalid transitions are ignored automatically—no need for guard clauses.

// Transition definition
idle: {
  on: { FETCH: 'loading' }  // "From idle, on FETCH, go to loading"
}

Key Takeaway: States define where you are, events define what happens, and transitions define the rules—creating impossible-to-break state logic that prevents bugs before they occur.