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()
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.
Preview the example live on StackBlitz:
Deploy the example using Vercel:
Execute create-next-app
with npm or Yarn to bootstrap the example:
npx create-next-app --example with-zustand with-zustand-app
# or
yarn create next-app --example with-zustand with-zustand-app
Deploy it to the cloud with Vercel (Documentation).