|
| 1 | +import { |
| 2 | + createContext as reactCreateContext, |
| 3 | + createElement, |
| 4 | + useContext, |
| 5 | + useRef, |
| 6 | + type ReactNode, |
| 7 | +} from "react"; |
| 8 | +import type { UseBoundStore, StoreApi } from "zustand"; |
| 9 | + |
| 10 | +type UseContextStore<T extends object> = { |
| 11 | + (): T; |
| 12 | + <U>(selector: (s: T) => U, equalityFn?: (a: T, b: T) => boolean): U; |
| 13 | +}; |
| 14 | + |
| 15 | +function createContext< |
| 16 | + TState extends object, |
| 17 | + TUseBoundStore extends UseBoundStore<StoreApi<object>> = UseBoundStore< |
| 18 | + StoreApi<object> |
| 19 | + >, |
| 20 | +>() { |
| 21 | + const ZustandContext = reactCreateContext<TUseBoundStore | undefined>( |
| 22 | + undefined, |
| 23 | + ); |
| 24 | + |
| 25 | + const Provider = ({ |
| 26 | + createStore, |
| 27 | + children, |
| 28 | + }: { |
| 29 | + createStore: () => TUseBoundStore; |
| 30 | + children: ReactNode; |
| 31 | + }) => { |
| 32 | + const storeRef = useRef<TUseBoundStore>(); |
| 33 | + |
| 34 | + if (!storeRef.current) { |
| 35 | + storeRef.current = createStore(); |
| 36 | + } |
| 37 | + |
| 38 | + return createElement( |
| 39 | + ZustandContext.Provider, |
| 40 | + { value: storeRef.current }, |
| 41 | + children, |
| 42 | + ); |
| 43 | + }; |
| 44 | + |
| 45 | + const useStore: UseContextStore<TState> = <StateSlice>( |
| 46 | + selector?: (s: TState) => StateSlice, |
| 47 | + equalityFn = Object.is, |
| 48 | + ) => { |
| 49 | + // ZustandContext value is guaranteed to be stable. |
| 50 | + const useProviderStore = useContext(ZustandContext); |
| 51 | + if (!useProviderStore) { |
| 52 | + throw new Error( |
| 53 | + "Seems like you have not used zustand provider as an ancestor.", |
| 54 | + ); |
| 55 | + } |
| 56 | + |
| 57 | + return useProviderStore(selector as (s: object) => StateSlice, equalityFn); |
| 58 | + }; |
| 59 | + |
| 60 | + return { |
| 61 | + Provider, |
| 62 | + ZustandContext, |
| 63 | + useStore, |
| 64 | + }; |
| 65 | +} |
| 66 | + |
| 67 | +export default createContext; |
0 commit comments