-
I am trying zustand with next.js based on with-zustand-example that depends on As |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 18 replies
-
Good point. zustand/context migration guidePreviously, we did something like this: import create from 'zustand'
import createContext from 'zustand/context'
const MyContext = createContext()
const createMyStore = () => create(...)
const App = () => (
<MyContext.Provider createStore={createMyStore}>
...
</MyContext.Provider>
)
const Component = () => {
const slice = MyContext.useStore(selector)
...
} With v4, it can be the following: import { createStore, useStore } from 'zustand'
import { createContext, useContext } from 'react'
const MyContext = createContext()
const createMyStore = () => createStore(...)
const App = () => {
const store = useRef(createMyStore()).current // or any better solution
return (
<MyContext.Provider value={store}>
...
</MyContext.Provider>
)
}
const Component = () => {
const store = useContext(MyContext)
const slice = useStore(store, selector)
...
} |
Beta Was this translation helpful? Give feedback.
-
How would this work when copying the ssr example? https://github.com/vercel/next.js/blob/canary/examples/with-zustand/lib/store.js |
Beta Was this translation helpful? Give feedback.
-
Has anyone done this with TS? The most basic example following the docs doesn't compile.
|
Beta Was this translation helpful? Give feedback.
-
The example https://github.com/vercel/next.js/tree/canary/examples/with-zustand seems to work fine for me, thanks a lot for making this. One question though: if I wanted to re-initialize / update the store on route change (after hydration) based on new data from In export const getStaticProps: GetStaticProps = async (context) => {
const { mainMenuData } = myFetchRequest()...
const store = initializeStore({ mainMenuData })
return {
props: {
initialStoreState: JSON.parse(JSON.stringify(store.getState())),
},
}
} This will work fine for first request but will not update In const StoreProvider = ({ children, ...props }: PropsWithChildren) => {
const storeRef = useRef<StoreType>()
if (!storeRef.current) { // this will block updating the values
storeRef.current = initializeStore(props)
}
return <Provider value={storeRef.current}>{children}</Provider>
} Can I just remove that check |
Beta Was this translation helpful? Give feedback.
-
I created npm package for Provider zustand |
Beta Was this translation helpful? Give feedback.
Good point.
We have an example in https://github.com/pmndrs/zustand/releases/tag/v4.0.0, but not migration guide.
zustand/context migration guide
Previously, we did something like this:
With v4, it can be the following: