🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Modeling UI State with XState Machines

React AdvancedđŸŸĸ Free Lesson

Every form that grew past a screen eventually collects the same debris: isSubmitting, hasError, showError, isEditing, showConfirm, step, maxStepReached, and a half dozen flags that individually make sense and collectively describe combinations that should be impossible. Bugs appear exactly there, in the combinations nobody wrote down, such as a retry button that works while the request is still in flight or a wizard that reports step four when validation on step two never passed. A state machine makes the impossible states unrepresentable, because the set of states is declared up front and only declared transitions can happen.

â„šī¸What you are really buying

Not the library. The discipline of writing down every state your component can be in, every event that can arrive, and what happens next, in one place that a reviewer can read without tracing assignments across four files.

Why boolean flags stop scaling

Three independent booleans produce eight combinations, and each additional flag doubles them. Most of those combinations are meaningless, but nothing prevents the code from producing them, so the component needs defensive checks in every render to handle a state that ought not to exist. The cost shows up as conditionals: rendering logic that asks three questions to decide one thing, and tests that must assert on flag combinations rather than on outcomes.

A machine inverts the relationship. The current state is a single value from a declared list, transitions are explicit, and anything not listed simply cannot occur. If payment can only be attempted from the editing state, then no amount of dispatching will submit from the middle of a retry, and the render function asks one question: which state am I in.

The transition table is the specification

The machine below models a checkout: idle, editing the form, validating, submitting to the payment provider, and then success or failure, with a retry path that returns to submission rather than duplicating the payment.

import { createMachine, assign } from 'xstate';

export const checkoutMachine = createMachine(
  {
    id: 'checkout',
    initial: 'idle',
    context: {
      cart: [],
      total: 0,
      attempt: 0,
      error: null,
      confirmation: null,
    },
    states: {
      idle: {
        on: { OPEN: 'editing' },
      },
      editing: {
        on: {
          SUBMIT: { target: 'validating', guard: 'cartHasItems' },
          CANCEL: { target: 'idle' },
        },
      },
      validating: {
        on: {
          VALID: { target: 'submitting', actions: 'countAttempt' },
          INVALID: { target: 'editing', actions: 'recordError' },
        },
      },
      submitting: {
        invoke: {
          src: 'chargeCard',
          onDone: {
            target: 'success',
            actions: assign({ confirmation: ({ event }) => event.data.receiptId }),
          },
          onError: {
            target: 'failure',
            actions: assign({ error: ({ event }) => event.message }),
          },
        },
      },
      success: {
        type: 'final',
      },
      failure: {
        on: {
          RETRY: { target: 'submitting', guard: 'canRetry' },
          EDIT: { target: 'editing' },
        },
      },
    },
  },
  {
    guards: {
      cartHasItems: ({ context }) => context.cart.length > 0,
      canRetry: ({ context }) => context.attempt < 3,
    },
    actions: {
      countAttempt: assign({ attempt: ({ context }) => context.attempt + 1 }),
      recordError: assign({ error: 'Cart is empty or an item is out of stock' }),
    },
    services: {
      chargeCard: async ({ context }) => {
        const res = await fetch('/api/checkout', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ items: context.cart, total: context.total }),
        });
        if (!res.ok) throw new Error(await res.text());
        return res.json();
      },
    },
  }
);

Reading that object answers most questions a new team member will ask. What can go wrong between validating and submitting? Nothing, because there is no event to interrupt it except the service resolving. Can a customer submit an empty cart? No, the guard rejects the transition. What happens if the third attempt fails? RETRY is no longer allowed, so the only path forward is EDIT. The specification and the implementation are the same document.

Guards, actions and context

Guards decide whether a transition is legal, actions run side effects that are safe to fire and forget, and context carries the data the machine needs. The distinction matters: a guard must be a pure function of the current snapshot, because it may be evaluated speculatively, while an action may call analytics or update external state. Mixing them produces a machine that behaves differently when evaluated twice.

import { useMachine } from '@xstate/react';
import { checkoutMachine } from './checkoutMachine';

export function CheckoutPanel({ cart, total }) {
  const [state, send] = useMachine(checkoutMachine, {
    input: { cart, total },
  });

  if (state.matches('idle')) {
    return <button onClick={() => send({ type: 'OPEN' })}>Start checkout</button>;
  }

  if (state.matches('editing') || state.matches('validating')) {
    return (
      <form
        onSubmit={(e) => {
          e.preventDefault();
          const address = new FormData(e.currentTarget).get('address');
          send(address ? { type: 'SUBMIT' } : { type: 'INVALID' });
        }}
      >
        <label htmlFor="address">Shipping address</label>
        <input id="address" name="address" required />
        <button type="submit">Pay now</button>
        <button type="button" onClick={() => send({ type: 'CANCEL' })}>Cancel</button>
      </form>
    );
  }

  if (state.matches('submitting')) {
    return <p role="status">Processing payment, attempt {state.context.attempt}...</p>;
  }

  if (state.matches('failure')) {
    return (
      <div role="alert">
        <p>Payment failed: {state.context.error}</p>
        <button onClick={() => send({ type: 'RETRY' })}>Retry</button>
        <button onClick={() => send({ type: 'EDIT' })}>Edit details</button>
      </div>
    );
  }

  return (
    <p role="status">
      Order confirmed, reference {state.context.confirmation}
    </p>
  );
}

Notice what the component no longer contains: no conditionals about whether an error message should show while loading, no disabled logic derived from three flags, no cleanup of a stale request when the user cancels. The machine owns the lifecycle, so the render function is a straight mapping from state to markup.

The states and events, written down

Part of the value is having the table at all. Before writing the machine, teams argue about behavior in pull requests; afterwards they argue about a table that can be reviewed in one screen.

Current stateEventGuardNext stateSide effect
idleOPENnoneeditingnone
editingSUBMITcart has itemsvalidatingnone
editingSUBMITcart emptyeditingshow error
validatingVALIDnonesubmittingincrement attempt, call service
validatingINVALIDnoneeditingrecord error message
submittingservice resolvesnonesuccessstore confirmation
submittingservice rejectsnonefailurestore error
failureRETRYattempt less than threesubmittingcall service again
failureRETRYattempt at limitfailurereject event
failureEDITnoneeditingnone

Product managers can read this table and correct it, which is a category of bug that never reaches code review. The row that says RETRY is rejected at the limit is usually the row that sparks the most discussion, and that discussion is precisely the one to have before implementation rather than after a customer retries a failed charge six times.

Testing becomes exhaustive instead of representative

Because transitions are data, a test can walk every path rather than guessing at one. A small helper that sends a sequence of events and asserts the resulting state covers the happy path, every rejection, and the boundary at the retry limit, and it does so without rendering a component or mocking a network layer beyond the service itself. Machine tests run in milliseconds, which means they run on every commit instead of nightly.

The additional payoff is event tracing. Interpreted machines can log each transition with the event that caused it, so a bug report becomes a sequence of lines showing exactly which event arrived from which state. Debugging stops being a question of which piece of state was stale and becomes a question of which event should not have been allowed. Visualizers take the same trace and draw the graph, which is often the fastest way to explain a flow to someone who did not write it.

When a machine is the wrong tool

Two booleans that never interact do not need a machine, and neither does a component whose only states are loading and loaded. The threshold is usually when you catch yourself writing a comment that says "this should not be possible" or adding a guard to a render function to defend against a state you did not intend to create.

There is also a cost. Every new state is a change to a shared definition, so a machine that spans several components needs the same care as any shared module. Keep machines local to the feature that owns the flow, prefer several small machines over one global one, and let simple components stay simple. A useful rule is to start with plain state and promote to a machine the moment a second boolean appears that must agree with the first, because that agreement is exactly what flags fail to enforce.

Common Mistakes

Encoding illegal combinations as flags and defending against them in every render

Fix: Model only the states that are valid, so an illegal combination cannot be expressed or reached.

Performing side effects inside guards instead of actions or services

Fix: Keep guards pure, move effects to actions and asynchronous work to invoked services.

Building one global machine that owns unrelated flows

Fix: Keep a machine local to the feature and let components without branching logic stay ordinary components.

Driving the machine from component state so both have to agree

Fix: Let the machine be the single source of truth and derive rendering from its snapshot alone.

Key Takeaways

  • Boolean flags multiply into impossible combinations; a machine declares the states and only the declared transitions
  • Guards must be pure, actions handle side effects, and services own asynchronous work so the lifecycle stays testable
  • The transition table doubles as a specification that product and engineering can review before any code is written
  • Rendering becomes a direct map from state to markup, which removes the conditional debris that causes most UI bugs
  • Machines pay for themselves once a flow has more than two booleans or a comment defending against an impossible state
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement