We will be updating this guide soon based on our discussion in GitHub #2740.
Challenges with Next.js
Keep in mind that Zustand store is a global variable (module state), which makes it optional to use Context. These challenges include:Per-request Store
A Next.js server can handle multiple requests simultaneously. The store should be created per request and not shared across requests.
SSR Friendly
Next.js applications render twice—on the server and client. Different outputs cause hydration errors.
SPA Routing
Next.js supports hybrid client-side routing. To reset a store, initialize it at the component level using Context.
Server Caching
Recent Next.js versions (App Router) support aggressive server caching. Zustand’s module state is compatible with this.
Recommendations
Creating a Store Per Request
Configure TypeScript
Set up your
tsconfig.json for Next.js:tsconfig.json
Remove all comments from your
tsconfig.json file.Initialize the Store
Create a store factory function using
zustand/vanilla:src/stores/counter-store.ts
Usage with Different Architectures
Next.js offers two architectures: Pages Router and App Router. Usage is similar with slight differences.- Pages Router
- App Router
Related Guides
SSR and Hydration
Learn about server-side rendering and hydration concepts
TypeScript
Type-safe patterns for Zustand stores