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

Creating Your First Machine with createMachine

Building a simple toggle or fetch machine to understand XState's configuration object syntax.

Creating Your First Machine with createMachine

What you'll learn: How to define a state machine in XState using createMachine and its configuration object syntax.

Now that you understand XState's core concepts—states, events, and transitions—it's time to actually build one. XState provides the createMachine function to define machines using a configuration object that describes all possible states and how they transition.

The Basic Structure

Think of createMachine as drawing a map of your component's behavior. You provide an object that specifies:

  • An id for debugging
  • The initial state where the machine starts
  • A states object containing every possible state
  • Inside each state, an on object mapping events to target states

A Simple Toggle Machine

Here's a basic toggle machine—like a light switch:

import { createMachine } from 'xstate';

const toggleMachine = createMachine({
  id: 'toggle',
  initial: 'inactive',
  states: {
    inactive: {
      on: {
        TOGGLE: 'active'
      }
    },
    active: {
      on: {
        TOGGLE: 'inactive'
      }
    }
  }
});

This configuration says: "Start in inactive. When a TOGGLE event arrives, move to active. From active, TOGGLE returns to inactive."

Reading the Configuration

The nested structure mirrors how you think: "When I'm in this state and this event happens, go to that state." No manual boolean flipping, no if/else chains—just a declarative map of behavior.

The machine definition is pure—just a configuration object. Later lessons will show you how to interpret and use it in React components.

Key Takeaway: createMachine takes a configuration object describing states and transitions, creating a declarative, visual map of your component's behavior that's easy to reason about and modify.