Replies: 2 comments 7 replies
|
@Lunrk would you mind creating a demo on stackblitz, I'd be happy to help |
|
Yes — the main thing with SSR/framework mode is to avoid a module-level singleton store when request-specific state is involved. The safe patterns are usually:
If the state is truly client-only, you can also mount that subtree behind a client boundary and initialize/sync it in an effect. The part that usually causes SSR errors is not Zustand itself — it’s sharing one global store across requests or touching browser APIs too early. |
|
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 |
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
All reactions