Back to Blog
DevelopmentNovember 17, 202610 min read

State Machines for UI: Goodbye to Impossible States

Loose booleans create impossible states. How to model a screen with explicit states using a hand-written reducer, and why UI bugs disappear on their own.

IM
Ignacio MelendezFull-Stack & Game Developer
State Machines for UI: Goodbye to Impossible States

QA shares a screenshot of the app's orders screen. At the top, a red banner: "We couldn't load your orders". Below it, the spinner turning. But the curious part is that, below the spinner, the list of orders was perfectly loaded. Three things that should never coexist, painted at the same time in the app.

The bug was easy to reproduce: with no connection, open the screen. The load fails and the banner shows up. Get the connection back, tap "Retry". The handler did setIsLoading(true) and fired the request, but nobody had thought of adding a setError(null). While the request was in flight you could see the error and the spinner. When the response arrived, setData(orders) and setIsLoading(false), and the error was still there, on top of a list that had loaded fine.

The fix was no more than one line. The worrying part was that the code allowed that state without complaining. No type, no test and no review would have warned about it, because for TypeScript, isLoading: true with error: Error and data: Order[] was a valid combination.

That's a clear example of poor state management in an app's UI. And this article is precisely about fixing those cases.

1. Four booleans, sixteen screens

In any React or React Native project, you end up using a useState for every condition, with values that have to decide what to paint.

1function OrdersScreen() {
2  const [isLoading, setIsLoading] = useState(false)
3  const [error, setError] = useState<Error | null>(null)
4  const [data, setData] = useState<Order[] | null>(null)
5  const [isRefreshing, setIsRefreshing] = useState(false)
6
7  async function load() {
8    setIsLoading(true)
9    try {
10      const orders = await fetchOrders()
11      setData(orders)
12    } catch (e) {
13      setError(e as Error)
14    } finally {
15      setIsLoading(false)
16    }
17  }
18
19  useEffect(() => {
20    load()
21  }, [])
22
23  if (isLoading && !data) return <ActivityIndicator />
24  if (error && !data) return <ErrorBanner onRetry={load} />
25  if (!isLoading && !error && data?.length === 0) return <EmptyState />
26
27  return (
28    <FlatList
29      data={data ?? []}
30      refreshing={isRefreshing}
31      onRefresh={load}
32      renderItem={({ item }) => <OrderRow order={item} />}
33    />
34  )
35}

You end up with four independent variables: three booleans (counting error and data as "there is or there isn't") plus isRefreshing (which, in this case, onRefresh doesn't even update). That results in 16 possible combinations. But the screen only makes sense in four or five: loading for the first time, error with no data, empty list, list with data, and list with data while refreshing. The other eleven are impossible states the code doesn't prevent, and every if in the render is an attempt to guess which one applies.

The cause is that consistency between variables depends on every handler updating all of them in the right order, and every new handler is a chance to forget one of the previous ones. On top of that, the render is left to decide priorities, which end up defined by the order of the if statements, something that is neither scalable nor intuitive.

If a combination of state makes no sense on screen, it shouldn't be representable in code.

2. One discriminated union per screen

The first step doesn't require installing any library. It consists of changing the mindset from "is it loading? is there an error? is there data?" to "what state is the screen in right now?". Each state carries exactly the data that makes sense in it.

In TypeScript that's achieved with a discriminated union: a type made of several variants that share a literal field that tells them apart (in this case status).

1type OrdersState =
2  | { status: 'idle' }
3  | { status: 'loading' }
4  | { status: 'success'; orders: Order[] }
5  | { status: 'empty' }
6  | { status: 'refreshing'; orders: Order[] }
7  | { status: 'failure'; error: Error; attempts: number }

This way, orders only exists in success and refreshing. If you try to read state.orders inside case 'failure', the compiler fails and the developer finds out right away. The state QA found (error, spinner and list at the same time) can no longer happen, because there's no variant that has error and orders at the same time.

The assertNever in the default adds a layer of safety during development itself. If tomorrow { status: 'offline' } is added to the union and someone forgets to paint it in the UI, state stops being never in that branch and TypeScript throws a compile error. The render becomes exhaustive by type.

idle may look redundant when the screen loads on mount, but it can be useful to keep it. It represents "I haven't asked for anything yet", and it's the natural initial state for screens that load on demand (a search, a form). Having it explicit avoids initializing in loading and having a test see a spinner nobody has triggered yet.

3. Transitions

A discriminated union describes the states, but it doesn't stop you from jumping from one to another in any way.

Using a setState in each handler, you can go from failure to success without having loaded anything. This is where the other half of the state machine comes in: transitions.

A transition is a rule of the form "being in X, if event Y arrives, I go to Z". Events represent what happens (the user taps retry, the request responds, an error arrives...), and the next state depends on both. useReducer fits that way of thinking without adding dependencies.

1type OrdersEvent =
2  | { type: 'FETCH' }
3  | { type: 'RESOLVE'; orders: Order[] }
4  | { type: 'REJECT'; error: Error }
5  | { type: 'RETRY' }
6  | { type: 'REFRESH' }
7
8const MAX_ATTEMPTS = 3
9
10export function ordersReducer(state: OrdersState, event: OrdersEvent): OrdersState {
11  switch (state.status) {
12    case 'idle':
13      if (event.type === 'FETCH') return { status: 'loading' }
14      return state
15
16    case 'loading':
17      if (event.type === 'RESOLVE') {
18        return event.orders.length === 0
19          ? { status: 'empty' }
20          : { status: 'success', orders: event.orders }
21      }
22      if (event.type === 'REJECT') {
23        return { status: 'failure', error: event.error, attempts: 1 }
24      }
25      return state
26
27    case 'failure':
28      if (event.type === 'RETRY' && state.attempts < MAX_ATTEMPTS) {
29        return { status: 'loading' }
30      }
31      return state
32
33    case 'success':
34      if (event.type === 'REFRESH') return { status: 'refreshing', orders: state.orders }
35      return state
36
37    case 'refreshing':
38      if (event.type === 'RESOLVE') {
39        return event.orders.length === 0
40          ? { status: 'empty' }
41          : { status: 'success', orders: event.orders }
42      }
43      // If the refresh fails, I keep the list I already had.
44      if (event.type === 'REJECT') return { status: 'success', orders: state.orders }
45      return state
46
47    case 'empty':
48      if (event.type === 'REFRESH') return { status: 'loading' }
49      return state
50
51    default:
52      return assertNever(state)
53  }
54}

The outer switch is on the state, not on the event. Keep in mind that inside each case you need to look at the current state; otherwise it's just a setState with extra steps. By putting the state on the outside, each branch answers "which events make sense here", and everything else falls through to return state.

4. Events that don't belong are ignored

The final return state in each branch looks like filler, but it's what eliminates race conditions.

For example: a user enters the orders screen and the request takes a while; they do a "pull to refresh" on a version that already had the list cached, and the first request responds late. With a boolean, that setData value overwrites whatever is there, regardless of where on the screen the user is. With the reducer, a RESOLVE that arrives while in failure/empty does nothing, because that branch doesn't account for it.

The same happens with double taps on buttons. If the user taps "Retry" twice in a row, the first RETRY takes the machine to loading, and the second one reaches a state that doesn't know what to do with it. Some solutions would be disabling the button or using a useRef with a "loading" flag, but with the state machine, the protection lives directly in the structure.

Ignoring the event doesn't cancel the request that produced it. The late response is discarded, but the network call was made anyway. If the request has side effects on the server (a POST, a payment), you need to cancel it or make sure the backend is idempotent.

5. Guards, context and effects

A guard is a condition that decides whether a transition is available or not. In the previous example, RETRY only leads to loading if attempts < MAX_ATTEMPTS. The problem is where attempts lives.

Some data belongs to a variant (for example, the list of orders only exists when there is a list) and some belongs to the whole machine (like an attempt counter that has to survive passing through loading). The cleanest option is to separate them: the discriminated state on one side and the context on the other, inside the same object. The failure variant of OrdersState loses its attempts field, which moves up one level.

1type Machine = {
2  state: OrdersState
3  attempts: number
4}
5
6const canRetry = (m: Machine) => m.attempts < MAX_ATTEMPTS
7
8export function ordersMachine(m: Machine, event: OrdersEvent): Machine {
9  const { state } = m
10
11  if (state.status === 'loading' && event.type === 'REJECT') {
12    return {
13      state: { status: 'failure', error: event.error },
14      attempts: m.attempts + 1,
15    }
16  }
17
18  if (state.status === 'failure' && event.type === 'RETRY' && canRetry(m)) {
19    return { ...m, state: { status: 'loading' } }
20  }
21
22  if (state.status === 'loading' && event.type === 'RESOLVE') {
23    return {
24      state: event.orders.length === 0
25        ? { status: 'empty' }
26        : { status: 'success', orders: event.orders },
27      attempts: 0,
28    }
29  }
30
31  // ...rest of the transitions same as before
32  return m
33}

The request isn't fired from the button handler, but as a reaction to entering loading or refreshing. The button only sends RETRY. If the machine decides it can't retry (the guard returns false), the state doesn't change, the effect doesn't run again and no request goes out. The "do I make the call?" decision lives in a single place and you don't have to keep managing it everywhere.

The cleanup with abort() covers the screen unmounting and any exit from the loading state before the response arrives. Together with the return state from the previous section, the late response is discarded twice: by the network and by the machine.

6. How to test it

The best consequence of moving the logic into a machine is that you no longer need to render screens to test it. The reducer is a pure function: state and event in, state out. The tests read like the screen's specification.

TypeScript
1import { ordersMachine } from './ordersReducer'
2
3const failed = (attempts: number) => ({
4  state: { status: 'failure' as const, error: new Error('network') },
5  attempts,
6})
7
8describe('ordersMachine', () => {
9  it('moves to empty if the response has no orders', () => {
10    const next = ordersMachine(
11      { state: { status: 'loading' }, attempts: 0 },
12      { type: 'RESOLVE', orders: [] },
13    )
14    expect(next.state).toEqual({ status: 'empty' })
15  })
16
17  it('retries while attempts remain', () => {
18    const next = ordersMachine(failed(1), { type: 'RETRY' })
19    expect(next.state.status).toBe('loading')
20  })
21
22  it('does not retry once the limit is reached', () => {
23    const before = failed(3)
24    expect(ordersMachine(before, { type: 'RETRY' })).toBe(before)
25  })
26
27  it('ignores a response that arrives outside loading', () => {
28    const before = failed(1)
29    const next = ordersMachine(before, { type: 'RESOLVE', orders: [anOrder()] })
30    expect(next).toBe(before)
31  })
32})

The "ignores a response that arrives outside loading" test is the most valuable one, and it's almost impossible to write against the boolean version (you'd have to test every set of options). To reproduce a race condition with useState you'd have to mount the component, control the resolution order of two promises and check the result on screen.

With the machine it's one line: this event, in this state, changes nothing.

Component tests are still useful, but their goal changes: they don't check transition logic, they check that each state renders as it should. With React Native Testing Library one test per switch variant is enough, passing the state directly to renderOrders.

7. When it's not worth it

Not every useState is an impossible state waiting to happen. An open or closed modal is a boolean, and wrapping it in a { status: 'open' } | { status: 'closed' } union adds nothing. The rule I use is to count variables that depend on each other: if changing one forces you to change another to keep the screen consistent, there's a machine hiding there. If they're independent, booleans can be enough.

It also makes no sense to hand-write what a data library already solves. TanStack Query v5 exposes status as 'pending' | 'error' | 'success', and when you check status === 'success' TypeScript narrows data so it's no longer undefined. For a screen that only reads data, that's already a well-built discriminated union, with caching and request deduplication included. Your own machine makes sense when the flow goes beyond "fetch and paint": multi-step forms, wizards, players, payment flows, anything where the user and the network take turns pushing the state.

In my experience the natural sequence is this: discriminated union whenever there are several coupled variables, and a reducer with a switch on state when transitions show up that need protecting.

A state machine doesn't add complexity to the screen. The complexity was already there, spread across booleans. The machine writes it down in one place where it can be read and tested.

8. Conclusions

The error banner on top of a loaded list was a one-line bug, but the cause was design: four variables that had to move together and no structure forcing them to. Changing the model made that bug, and the ones like it, impossible to write.

  • Independent booleans produce 2^n combinations, and almost none of them make sense on screen.
  • A discriminated union with a status field limits states to the ones that exist and ties each piece of data to the variant where it makes sense.
  • An exhaustive switch with assertNever turns an unpainted state into a compile error.
  • In the reducer, the outer switch is on the state, not the event. Events that don't belong return the state as is, and that removes races and double taps.
  • Data that survives between states (attempts, timers) goes in a separate context, and guards decide based on it.
  • Effects fire when entering a state, not from handlers. The button sends an event and the machine decides whether there's a request.
  • Logic is tested without rendering: state plus event, expected state.
  • For read-only screens, TanStack Query already gives you the discriminated state.

Over time, what has changed most is the order in which I think about a screen. I used to start with the JSX and add useState as I needed it. Now I start with the list of states and the events that move between them, and the JSX comes out of a switch almost on its own.

Related Articles

View all articles
The Journey of an Error: From a Backend 500 to the Message the User Sees

The Journey of an Error: From a Backend 500 to the Message the User Sees

An error crosses four layers before it reaches the user: the HTTP interceptor, the mapping to domain errors, the default behavior policy, and the render safety net. Three implementations (TypeScript, Kotlin and Swift) of the same pattern.

Repository Pattern: Your UI Shouldn't Know Where Data Comes From

Repository Pattern: Your UI Shouldn't Know Where Data Comes From

An interface that hides whether data comes from the network, cache, or disk. How to swap the source without touching a single screen.