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

State Machines vs Ad-Hoc State

Why modeling UI as a state machine eliminates impossible states and makes logic explicit and testable.

State Machines vs Ad-Hoc State

What you'll learn: Why modeling UI as a state machine eliminates impossible states and makes logic explicit and testable.

The Problem with Ad-Hoc State

When you manage state with multiple booleans or strings, you can accidentally create impossible states. Imagine a data fetching component:

const [isLoading, setIsLoading] = useState(false);
const [isError, setIsError] = useState(false);
const [data, setData] = useState(null);

What happens if isLoading and isError are both true? Or if data exists but isError is true? These combinations don't make sense, yet nothing prevents them. You're relying on discipline to keep them in sync.

The State Machine Approach

A state machine defines explicit states and allowed transitions. For the same scenario:

const [state, setState] = useState('idle'); // 'idle' | 'loading' | 'success' | 'error'

Now you have exactly four possibilities. You can never be "loading and errored" simultaneously. The state machine makes impossible states literally impossible.

Why This Matters

Clarity: Your logic becomes self-documenting. If you see state === 'loading', you know exactly what's happening—no cross-referencing multiple flags.

Testability: Testing "what happens when loading fails" is straightforward: transition from 'loading' to 'error' and verify behavior. No need to coordinate multiple state variables.

Predictability: Transitions are explicit. You move from 'idle' to 'loading' on fetch start, then to 'success' or 'error'. The flow is a clear map, not a tangled web of if statements.

The Analogy

Think of a traffic light: it's red, yellow, or green—never "kind of red and a little green." State machines enforce that same clarity in your UI logic.

Key Takeaway: Modeling UI state as a state machine eliminates impossible states by making valid states and transitions explicit, resulting in code that's clearer, safer, and easier to test.