30 lines
954 B
TypeScript
30 lines
954 B
TypeScript
import { createContext, type PropsWithChildren, useContext, useRef } from 'react';
|
|
import { type StoreApi, useStore } from 'zustand';
|
|
|
|
export function createZustandStore<S>(createStore: () => StoreApi<S>) {
|
|
type ZustandStoreApi = StoreApi<S>;
|
|
|
|
const StoreContext = createContext<undefined | ZustandStoreApi>(undefined);
|
|
|
|
function Provider({ children }: Readonly<PropsWithChildren>) {
|
|
const storeRef = useRef<null | ZustandStoreApi>(null);
|
|
if (storeRef.current === null) {
|
|
storeRef.current = createStore();
|
|
}
|
|
|
|
return <StoreContext value={storeRef.current}>{children}</StoreContext>;
|
|
}
|
|
|
|
const useZustandStore = <T,>(selector: (store: S) => T): T => {
|
|
const orderStoreContext = useContext(StoreContext);
|
|
|
|
if (!orderStoreContext) {
|
|
throw new Error(`useZustandStore must be used within OrderStoreProvider`);
|
|
}
|
|
|
|
return useStore(orderStoreContext, selector);
|
|
};
|
|
|
|
return { Provider, useZustandStore };
|
|
}
|