Unverified Commit 60d844c6 authored by Munawwar's avatar Munawwar Committed by GitHub

updated zustand example (#24884)

..to use new zustand/context module from zustand 3.5.0. Also fixed code for merging states on client-side navigation.


## Documentation / Examples

- [x] Make sure the linting passes
parent 656c2ef6
...@@ -10,7 +10,7 @@ To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.j ...@@ -10,7 +10,7 @@ To illustrate SSG and SSR, go to `/ssg` and `/ssr`, those pages are using Next.j
The trick here for supporting universal Zustand is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`. The trick here for supporting universal Zustand is to separate the cases for the client and the server. When we are on the server we want to create a new store every time, otherwise different users data will be mixed up. If we are in the client we want to use always the same store. That's what we accomplish on `store.js`.
All components have access to the Zustand store using `useStore`. All components have access to the Zustand store using `useStore()` returned from zustand's `createContext()` function.
On the server side every request initializes a new store, because otherwise different user data can be mixed up. On the client side the same store is used, even between page changes. On the server side every request initializes a new store, because otherwise different user data can be mixed up. On the client side the same store is used, even between page changes.
......
import { useStore } from '../lib/zustandProvider' import { useStore } from '../lib/store'
import shallow from 'zustand/shallow' import shallow from 'zustand/shallow'
const useClock = () => { const useClock = () => {
......
import { useStore } from '../lib/zustandProvider' import { useStore } from '../lib/store'
import shallow from 'zustand/shallow' import shallow from 'zustand/shallow'
const useCounter = () => { const useCounter = () => {
const { count, increment, decrement, reset } = useStore( const { count, increment, decrement, reset } = useStore(
......
...@@ -2,7 +2,7 @@ import useInterval from '../lib/useInterval' ...@@ -2,7 +2,7 @@ import useInterval from '../lib/useInterval'
import Clock from './clock' import Clock from './clock'
import Counter from './counter' import Counter from './counter'
import Nav from './nav' import Nav from './nav'
import { useStore } from '../lib/zustandProvider' import { useStore } from '../lib/store'
export default function Page() { export default function Page() {
const { tick } = useStore() const { tick } = useStore()
......
import { useMemo } from 'react' import { useLayoutEffect } from 'react'
import create from 'zustand' import create from 'zustand'
import createContext from 'zustand/context'
let store let store
...@@ -9,7 +10,9 @@ const initialState = { ...@@ -9,7 +10,9 @@ const initialState = {
count: 0, count: 0,
} }
function initStore(preloadedState = initialState) { export const { Provider, useStore } = createContext(initialState)
export const initializeStore = (preloadedState = {}) => {
return create((set, get) => ({ return create((set, get) => ({
...initialState, ...initialState,
...preloadedState, ...preloadedState,
...@@ -37,31 +40,30 @@ function initStore(preloadedState = initialState) { ...@@ -37,31 +40,30 @@ function initStore(preloadedState = initialState) {
})) }))
} }
export const initializeStore = (preloadedState) => { export function useHydrate(initialState) {
let _store = store ?? initStore(preloadedState) let _store = store ?? initializeStore(initialState)
// For SSR & SSG, always use a new store.
if (typeof window !== 'undefined') {
// For CSR, always re-use same store.
if (!store) {
store = _store
}
// After navigating to a page with an initial Zustand state, merge that state // And if initialState changes, then merge states in the next render cycle.
// with the current state in the store, and create a new store //
if (preloadedState && store) { // eslint complaining "React Hooks must be called in the exact same order in every component render"
_store = initStore({ // is ignorable as this code runs in the same order in a given environment (CSR/SSR/SSG)
...store.getState(), // eslint-disable-next-line react-hooks/rules-of-hooks
...preloadedState, useLayoutEffect(() => {
}) if (initialState && store) {
// Reset the current store store.setState({
store = undefined ...store.getState(),
...initialState,
})
}
}, [initialState])
} }
// For SSG and SSR always create a new store
if (typeof window === 'undefined') return _store
// Create the store once in the client
if (!store) store = _store
return _store return _store
} }
export function useHydrate(initialState) {
const state =
typeof initialState === 'string' ? JSON.parse(initialState) : initialState
const store = useMemo(() => initializeStore(state), [state])
return store
}
import { createContext, useContext } from 'react'
export const StoreContext = createContext(null)
export const StoreProvider = ({ children, store }) => {
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>
}
export const useStore = (selector, eqFn) => {
const store = useContext(StoreContext)
const values = store(selector, eqFn)
return values
}
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
"next": "latest", "next": "latest",
"react": "^16.9.0", "react": "^16.9.0",
"react-dom": "^16.9.0", "react-dom": "^16.9.0",
"zustand": "3.1.3" "zustand": "3.5.0"
}, },
"license": "MIT" "license": "MIT"
} }
import { StoreProvider } from '../lib/zustandProvider' import { useHydrate, Provider } from '../lib/store'
import { useHydrate } from '../lib/store'
export default function App({ Component, pageProps }) { export default function App({ Component, pageProps }) {
const store = useHydrate(pageProps.initialZustandState) const store = useHydrate(pageProps.initialZustandState)
return ( return (
<StoreProvider store={store}> <Provider initialStore={store}>
<Component {...pageProps} /> <Component {...pageProps} />
</StoreProvider> </Provider>
) )
} }
...@@ -14,6 +14,10 @@ export function getServerSideProps() { ...@@ -14,6 +14,10 @@ export function getServerSideProps() {
zustandStore.getState().tick(Date.now(), false) zustandStore.getState().tick(Date.now(), false)
return { return {
props: { initialZustandState: JSON.stringify(zustandStore.getState()) }, props: {
// the "stringify and then parse again" piece is required as next.js
// isn't able to serialize it to JSON properly
initialZustandState: JSON.parse(JSON.stringify(zustandStore.getState())),
},
} }
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment