Replies: 2 comments 7 replies
-
|
@Lunrk would you mind creating a demo on stackblitz, I'd be happy to help |
Beta Was this translation helpful? Give feedback.
7 replies
-
|
The SSR error happens because Zustand stores hold state in module-level singletons, which get shared across requests on the server (causing state leaks between users). Recommended pattern for Zustand + React Router v7 (framework/SSR mode): // store.ts — create a store factory, NOT a singleton
import { create } from 'zustand'
export const createAppStore = () => create((set) => ({
count: 0,
increment: () => set((s) => ({ count: s.count + 1 })),
}))
export type AppStore = ReturnType<typeof createAppStore>// context.tsx — provide store per-request via React context
import { createContext, useContext, useRef } from 'react'
import { useStore } from 'zustand'
import { createAppStore, type AppStore } from './store'
const StoreContext = createContext<AppStore | null>(null)
export function StoreProvider({ children }: { children: React.ReactNode }) {
const storeRef = useRef<AppStore>()
if (!storeRef.current) {
storeRef.current = createAppStore()
}
return (
<StoreContext.Provider value={storeRef.current}>
{children}
</StoreContext.Provider>
)
}
export function useAppStore<T>(selector: (state: ReturnType<AppStore['getState']>) => T) {
const store = useContext(StoreContext)
if (!store) throw new Error('Missing StoreProvider')
return useStore(store, selector)
}// root.tsx — wrap your app
import { StoreProvider } from './context'
export default function App() {
return (
<StoreProvider>
<Outlet />
</StoreProvider>
)
}This pattern:
@Lunrk The key insight is: never use |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello there !
I would like to know if there is any recommanded way to implement zustand for client side only in a React Router v7 app, I tried adding a Zustand store to some of my page / components but then I just get SSR error... May be this is not the right place and I should be asking on react router repo, but I was thinking may be some of you can get the answer !
Thanks a lot for your help
Beta Was this translation helpful? Give feedback.
All reactions