One shared instance between multiple React components #1754
-
If I wanted to share a single instance of my state machine in multiple React components, how would I go about it? The way I see it there are two possible solutions:
or maybe there's another way that I'm missing. |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 21 replies
-
Both are IMHO OK. Regarding your „state will be held in machine rather than in context” part - isnt this part if the point of using a machine? This works pretty much the same as with Redux - you externalize the state from React (either to XState or to Redux) and use context to subscribe to changes. |
Beta Was this translation helpful? Give feedback.
-
I'm currently writing an article on this, but I'd recommend doing it through context: const ServiceContext = React.createContext();
const App = ({ children }) => {
const [_state, _send, service] = useMachine(someMachine);
return (
<ServiceContext.Provider value={service}>
{children}
</ServiceContext.Provider>
);
}
// in a child...
const Child = () => {
const service = React.useContext(ServiceContext);
const [state, send] = useService(service);
// ...
} The pattern above feels pretty natural and idiomatic to React. |
Beta Was this translation helpful? Give feedback.
-
What about using a singleton where the machine is started in its file and the running service is exported? Then every other file importing it would get the same running service? This has been working for me; anything I'm missing? // my-service.js
const myMachine = Machine();
export const myService = interpret(myMachine);
myService.start(); Then in multiple other files: import { useService } from '@xstate/react';
import { myService } from './my-service';
const MyComponent = () => {
const [state, sendEvent] = useService(myService);
} import { useService } from '@xstate/react';
import { myService } from './my-service';
const MyOtherComponent = () => {
const [state, sendEvent] = useService(myService);
} |
Beta Was this translation helpful? Give feedback.
-
How to achieve this in the current xstate versions? |
Beta Was this translation helpful? Give feedback.
-
It works but I have some trouble to get I described it in the offical discord channel from Stately as well. You can find it here. It is basically about that: Someone else had the problem as well. |
Beta Was this translation helpful? Give feedback.
I'm currently writing an article on this, but I'd recommend doing it through context:
The pattern above feels pretty natural and idiomatic to React.