Skip to content

React Integration

import { useMachine } from "matchina/react";

Then, inside your component,

useMachine(machine);

That’s it!

import { useMachine } from "matchina/react";
const MyComponent = () => {
useMachine(machine);
return (
<div>
State: {machine.state}
<button onClick={() => machine.send("next")}>Next</button>
</div>
);
};

When using state machines with React, consider these tips for better performance:

  1. Memoize machine creation with useMemo when machine definition depends on props
  2. Use selective rendering with pattern matching to only render what’s needed
  3. Extract complex components into separate components to limit re-renders
// Good - Selective rendering with pattern matching
function UserView() {
useMachine(userMachine);
// Only the relevant section will re-render when state changes
return (
<div>
<Header /> {/* Won't re-render on state changes */}
<Sidebar /> {/* Won't re-render on state changes */}
{userMachine.state.match({
Loading: () => <LoadingSpinner />,
Error: ({ message }) => <ErrorMessage message={message} />,
LoggedIn: (user) => <UserProfile user={user} />,
LoggedOut: () => <LoginForm onLogin={userMachine.login} />,
})}
</div>
);
}

Now that you understand React integration, explore these related guides:

  • Promises - Learn more about promise machines
  • Lifecycle - Understand the full lifecycle system
  • Effects - Manage side effects with state machines