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

Guards: Conditional Transitions

Using guard functions to conditionally allow or block transitions based on context or event data.

Guards: Conditional Transitions

What you'll learn: How to use guard functions in XState to allow or block state transitions based on runtime conditions.

The Bouncer at the Door

Guards are like bouncers at a club entrance—they check credentials before letting someone in. In state machines, a guard is a function that evaluates whether a transition should happen. If the guard returns true, the transition proceeds. If false, the machine stays in its current state.

Without guards, every event would unconditionally trigger its transition. But real applications need logic: "only submit if the form is valid," "only proceed if the user has credits," "only open the door if authenticated."

How Guards Work

Guards are pure functions that receive the machine's context and the event data. They return a boolean:

const doorMachine = createMachine({
  context: { hasKey: false },
  initial: 'locked',
  states: {
    locked: {
      on: {
        UNLOCK: {
          target: 'unlocked',
          cond: (context, event) => context.hasKey
        }
      }
    },
    unlocked: { /* ... */ }
  }
});

Here, the UNLOCK event only transitions to unlocked if context.hasKey is true. Without the key, the machine ignores the event.

Named Guards for Reusability

You can define guards separately for clarity and reuse:

const formMachine = createMachine({
  context: { email: '' },
  /* ... */
}, {
  guards: {
    isValidEmail: (context) => context.email.includes('@')
  }
});

Then reference by name: cond: 'isValidEmail'.

Key Takeaway: Guards let you conditionally allow or block transitions based on context or event data, keeping your state logic precise and your machine states meaningful—only valid transitions happen.