Skip to content

Commit

Permalink
updated zustand example for 3.5.4+ interface change (#27229)
Browse files Browse the repository at this point in the history
## Documentation / Examples

- [✓] Make sure the linting passes
  • Loading branch information
Munawwar authored Jul 16, 2021
1 parent 530a2a3 commit dd029f5
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 27 deletions.
43 changes: 20 additions & 23 deletions examples/with-zustand/lib/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
2 changes: 1 addition & 1 deletion examples/with-zustand/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
6 changes: 3 additions & 3 deletions examples/with-zustand/pages/_app.js
Original file line number Diff line number Diff line change
@@ -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 (
<Provider initialStore={store}>
<Provider createStore={createStore}>
<Component {...pageProps} />
</Provider>
)
Expand Down

0 comments on commit dd029f5

Please sign in to comment.