Skip to content

Instantly share code, notes, and snippets.

@marcandrewb
Forked from evgeniyPP/GlobalStateProvider.tsx
Created January 19, 2023 20:40
Show Gist options
  • Save marcandrewb/7cc1b7cd229e56e1918fe7bc0d5997a5 to your computer and use it in GitHub Desktop.
Save marcandrewb/7cc1b7cd229e56e1918fe7bc0d5997a5 to your computer and use it in GitHub Desktop.
XState global state machine hook
import { createContext } from 'react';
import { InterpreterFrom } from 'xstate';
import { useInterpret } from '@xstate/react';
import { someMachine } from './someMachine';
export const GlobalStateContext = createContext({ someService: {} as InterpreterFrom<typeof someMachine> });
export const GlobalStateProvider = (props: React.PropsWithChildren) => {
const someService = useInterpret(someMachine);
return (
<GlobalStateContext.Provider value={{ someService }}>
{props.children}
</GlobalStateContext.Provider>
);
};
import { useContext } from 'react';
import { useSelector } from '@xstate/react';
import type { StateFrom } from 'xstate';
import { GlobalStateContext } from '../GlobalStateProvider';
import type { someMachine } from './someMachine';
export function useSomeMachine() {
const context = useContext(GlobalStateContext);
function select<T>(cb: (state: StateFrom<typeof someMachine>) => T): T {
return useSelector(context.someService, cb);
}
return { select, send: context.someService.send };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment