← Lessons

quiz vs the machine

Gold1380

Frontend

Finite State Machines for UI

Model UI as explicit states and transitions to kill impossible bugs.

5 min read · core · beat Gold to climb

The mess of booleans

A component with isLoading, isError, and isSuccess flags can drift into impossible combinations like loading and error at once. A finite state machine replaces flags with one explicit state.

Core ideas

  • A machine has a finite set of states, and is in exactly one at a time.
  • Transitions move between states in response to events.
  • An event in a state where no transition exists is simply ignored, preventing invalid moves.

Example states

A data fetch might be idle, loading, success, or failure. A fetch event moves idle to loading. A resolve event moves loading to success.

Why it helps

Because only one state is active, you cannot render contradictory UI. The diagram doubles as documentation, and reviewers can see every path. Libraries formalize this, but the pattern works with a plain reducer too.

Key idea

A finite state machine makes UI a single explicit state with defined transitions, eliminating the impossible flag combinations that cause subtle bugs.

Check yourself

Answer to earn rating on the learn ladder.

1. How many states can a finite state machine occupy at one time?

2. What happens to an event with no defined transition in the current state?