Shaf Lab

State machines

Explicit models of states and transitions, with libraries such as XState.

A state machine is an explicit model of states and the events that move you between them. XState is a library that brings this idea to user interfaces and workflows, but the pattern is older than any one tool. You name the states, the transitions, and what is allowed in each state, instead of scattering boolean flags across a component.

This helps when a UI has real modes: idle, loading, editing, confirming, error. It also helps when a backend process should not skip a step. A machine is easier to test than a tangle of flags, and you can draw it, share it, and sometimes model-check the tricky bits.

Keep the machine small enough to see on one page. If you need a second machine, compose it rather than adding a dozen orthogonal flags to the first. Put effects — network calls, timers — in one place so they are easy to mock. The model should describe what the product does, not the implementation accidents of a particular framework.

If the flow has two or three states and never grows, a simple switch may be enough. Reach for an explicit machine when the number of modes, or the cost of a bad transition, starts to climb.