React Integration
In a nutshell
Section titled “In a nutshell”import { useMachine } from "matchina/react";
Then, inside your component,
useMachine(machine);
That’s it!
Example
Section titled “Example”import { useMachine } from "matchina/react";
const MyComponent = () => { useMachine(machine); return ( <div> State: {machine.state} <button onClick={() => machine.send("next")}>Next</button> </div> );};
Performance Considerations
Section titled “Performance Considerations”Preventing Unnecessary Renders
Section titled “Preventing Unnecessary Renders”When using state machines with React, consider these tips for better performance:
- Memoize machine creation with
useMemo
when machine definition depends on props - Use selective rendering with pattern matching to only render what’s needed
- Extract complex components into separate components to limit re-renders
// Good - Selective rendering with pattern matchingfunction 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> );}
Next Steps
Section titled “Next Steps”Now that you understand React integration, explore these related guides: