How do I subscribe to a store in Nextjs when store is wrapped in a React Context. #2534
-
I've implemented a React context provider shown below on my Next.js 14 app. It wraps my app to ensure that the store initializes with each client request, rather than persisting as a global store between server requests. While I understand it's not recommended practice, I'm experimenting with multiple stores. However, I'm facing a challenge in using "use client";
import { StoreApi, useStore } from "zustand";
import { createStore, IStore } from "@/stores/store";
import { createContext, ReactNode, useContext, useRef } from "react";
const StoreContext = createContext<StoreApi<IStore> | null>(null);
type StoreProviderProps = Readonly<{
children: ReactNode;
}>;
export function StoreProvider({ children }: StoreProviderProps) {
const storeRef = useRef<StoreApi<IStore>>();
if (!storeRef.current) {
storeRef.current = createStore();
}
return (
<StoreContext.Provider value={storeRef.current}>
{children}
</StoreContext.Provider>
);
}
export function useStore(): IStore {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error(`useStore must be used within StoreProvider`);
}
return useStore(storeContext, selector)
}
export function useStore<T>(selector: (store: IStore) => T): T {
const storeContext = useContext(StoreContext);
if (!storeContext) {
throw new Error(`useStore must be used within StoreProvider`);
}
return useStore(storeContext, selector)
} Any guidance or examples on how to accomplish this would be greatly appreciated. Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
@KamaniBhavin here you go: export function useStore<T = IStore, U = T>(selector: (state: T) => U): [U, StoreApi<T>] {
const store = useContext(StoreContext);
if (store === undefined) {
throw new Error(`useStore must be used within StoreProvider`);
}
return [useStore(store, selector), store]
} |
Beta Was this translation helpful? Give feedback.
-
@dbritto-dev How do I use |
Beta Was this translation helpful? Give feedback.
@KamaniBhavin here you go: