diff --git a/examples/with-zustand/lib/store.js b/examples/with-zustand/lib/store.js index 75d296fa78ffa..bd5c6db2258e4 100644 --- a/examples/with-zustand/lib/store.js +++ b/examples/with-zustand/lib/store.js @@ -44,30 +44,27 @@ export const initializeStore = (preloadedState = {}) => { })) } -export function useHydrate(initialState) { - let _store = store ?? initializeStore(initialState) - +export function useCreateStore(initialState) { // For SSR & SSG, always use a new store. - if (typeof window !== 'undefined') { - // For CSR, always re-use same store. - if (!store) { - store = _store - } - - // And if initialState changes, then merge states in the next render cycle. - // - // eslint complaining "React Hooks must be called in the exact same order in every component render" - // is ignorable as this code runs in the same order in a given environment (CSR/SSR/SSG) - // eslint-disable-next-line react-hooks/rules-of-hooks - useLayoutEffect(() => { - if (initialState && store) { - store.setState({ - ...store.getState(), - ...initialState, - }) - } - }, [initialState]) + if (typeof window === 'undefined') { + return () => initializeStore(initialState) } - return _store + // For CSR, always re-use same store. + store = store ?? initializeStore(initialState) + // And if initialState changes, then merge states in the next render cycle. + // + // eslint complaining "React Hooks must be called in the exact same order in every component render" + // is ignorable as this code runs in same order in a given environment + // eslint-disable-next-line react-hooks/rules-of-hooks + useLayoutEffect(() => { + if (initialState && store) { + store.setState({ + ...store.getState(), + ...initialState, + }) + } + }, [initialState]) + + return () => store } diff --git a/examples/with-zustand/package.json b/examples/with-zustand/package.json index 0ed36281c6d5f..dd3e3052fcc3c 100644 --- a/examples/with-zustand/package.json +++ b/examples/with-zustand/package.json @@ -9,7 +9,7 @@ "next": "latest", "react": "^17.0.2", "react-dom": "^17.0.2", - "zustand": "3.5.1" + "zustand": "^3.5.4" }, "license": "MIT" } diff --git a/examples/with-zustand/pages/_app.js b/examples/with-zustand/pages/_app.js index 082837c7aac24..9488e2e3260b7 100644 --- a/examples/with-zustand/pages/_app.js +++ b/examples/with-zustand/pages/_app.js @@ -1,9 +1,9 @@ -import { useHydrate, Provider } from '../lib/store' +import { useCreateStore, Provider } from '../lib/store' export default function App({ Component, pageProps }) { - const store = useHydrate(pageProps.initialZustandState) + const createStore = useCreateStore(pageProps.initialZustandState) return ( - + )