Using Machines in React with useMachine
You'll learn how to integrate XState machines into React components using the useMachine hook from @xstate/react.
Bridging Machines and Components
You've created a state machine with createMachine, but it lives outside React's component world. The useMachine hook is your bridge—it connects your machine to React's rendering cycle, giving you the current state and a function to send events, similar to how useState returns state and a setter.
Think of useMachine like plugging in a sophisticated control panel. Your machine defines what states exist and how to transition between them. The hook gives you a live readout of the current state and buttons (the send function) to trigger those transitions.
The Hook Signature
import { useMachine } from '@xstate/react';
import { myMachine } from './myMachine';
function MyComponent() {
const [state, send] = useMachine(myMachine);
return (
<div>
<p>Current: {state.value}</p>
<button onClick={() => send('TOGGLE')}>
Toggle
</button>
</div>
);
}
You pass your machine to useMachine, and it returns an array with two elements:
state: The current state object (access the state name withstate.value)send: A function to dispatch events to the machine (likesend('EVENT_NAME'))
The hook automatically re-renders your component whenever the machine transitions to a new state.
Reacting to State
Use state.value to render conditionally or state.matches('stateName') to check specific states. The component stays in sync with your machine's declarative logic.
Key Takeaway: useMachine from @xstate/react connects XState machines to React components, returning the current state and a send function for dispatching events that trigger transitions.