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:
useMachine
hook.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.
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".
import { createMachine } from 'xstate';
const toggleMachine = createMachine({
initial: 'inactive',
states: {
inactive: {
on: { TOGGLE: 'active' }
},
active: {
on: { TOGGLE: 'inactive' }
}
}
});
export default toggleMachine;
'inactive'
.inactive
and active
.TOGGLE
event will switch between the inactive
and active
states.Next, we’ll integrate this state machine into a React component using the useMachine
hook from @xstate/react
.
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;
send
function to dispatch events.inactive
or active
).TOGGLE
event, which transitions between the states.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.
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.