Sviatoslav Oleksiv

Setting Up XState in a React Application

In the previous lesson, we introduced the concepts of finite state machines and how XState simplifies state management in modern React applications. In this lesson, we’ll walk you through the process of setting up XState in a React project.

By the end of this article, you'll be able to:

Step 1: Installing XState in a React Project

To get started, we need to install the XState package and its React bindings. Run the following commands to install them in your project:

npm install xstate @xstate/react

Alternatively, if you’re using yarn:

yarn add xstate @xstate/react

This will install the core XState library and the React-specific bindings that provide hooks like useMachine for integrating XState into your components.

Step 2: Creating a Simple State Machine

Once installed, let’s create a simple state machine. For this example, we’ll build a toggle machine that switches between two states: "active" and "inactive".

Create the Toggle Machine

import { createMachine } from 'xstate';

const toggleMachine = createMachine({
  initial: 'inactive',

  states: {
    inactive: {
      on: { TOGGLE: 'active' }
    },
    active: {
      on: { TOGGLE: 'inactive' }
    }
  }
});

export default toggleMachine;

Explanation:

Step 3: Integrating the Machine in a React Component

Next, we’ll integrate this state machine into a React component using the useMachine hook from @xstate/react.

Example: Toggle Component

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

const ToggleButton = () => {
  const [state, send] = useMachine(toggleMachine);

  return (
    <div>
      <p>The current state is {state.value}</p>
      <button onClick={() => send('TOGGLE')}>
        Toggle
      </button>
    </div>
  );
};

export default ToggleButton;

Explanation:

Step 4: Running the React App

Once you’ve integrated the state machine into your component, you can run your React application as usual. You should see a button that toggles the state between active and inactive when clicked.

npm start

Open your browser and see the toggle button in action.

Conclusion

In this lesson, you learned how to set up XState in a React project, define a simple state machine, and integrate it into a React component using the useMachine hook. In the next lesson, we will explore how to handle more complex state transitions and side effects with XState.


Next Lesson: Creating Your First State Machine