Skip to content
Myr

nextjs.md

This file

Path

docs/learn/guides/nextjs.md

316 lines · 8.6 KiB · Markdown

Last changed by

Change CounterStore type from intersection to union (#3565)Danilo Brittobefore adoptionb126c33

History of this file

Take it

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 1–88why, one step back
1---
2title: Setup with Next.js3nav: 154---56> [!NOTE]7> We will be updating this guide soon based on our discussion in https://github.com/pmndrs/zustand/discussions/2740.89[Next.js](https://nextjs.org) is a popular server-side rendering framework for React that presents10some unique challenges for using Zustand properly.11Keep in mind that Zustand store is a global12variable (AKA module state) making it optional to use a `Context`.13These challenges include:1415- **Per-request store:** A Next.js server can handle multiple requests simultaneously. This means16 that the store should be created per request and should not be shared across requests.17- **SSR friendly:** Next.js applications are rendered twice, first on the server18 and again on the client. Having different outputs on both the client and the server will result19 in "hydration errors." The store will have to be initialized on the server and then20 re-initialized on the client with the same data in order to avoid that. Please read more about21 that in our [SSR and Hydration](./ssr-and-hydration.md) guide.22- **SPA routing friendly:** Next.js supports a hybrid model for client side routing, which means23 that in order to reset a store, we need to initialize it at the component level using a24 `Context`.25- **Server caching friendly:** Recent versions of Next.js (specifically applications using the App26 Router architecture) support aggressive server caching. Due to our store being a **module state**,27 it is completely compatible with this caching.2829We have these general recommendations for the appropriate use of Zustand:3031- **No global stores** - Because the store should not be shared across requests, it should not be defined32 as a global variable. Instead, the store should be created per request.33- **React Server Components should not read from or write to the store** - RSCs cannot use hooks or context. They aren't34 meant to be stateful. Having an RSC read from or write values to a global store violates the35 architecture of Next.js.3637### Creating a store per request3839Let's write our store factory function that will create a new store for each40request.4142```json43// tsconfig.json44{45 "compilerOptions": {46 "lib": ["dom", "dom.iterable", "esnext"],47 "allowJs": true,48 "skipLibCheck": true,49 "strict": true,50 "noEmit": true,51 "esModuleInterop": true,52 "module": "esnext",53 "moduleResolution": "bundler",54 "resolveJsonModule": true,55 "isolatedModules": true,56 "jsx": "preserve",57 "incremental": true,58 "plugins": [59 {60 "name": "next"61 }62 ],63 "paths": {64 "@/*": ["./src/*"]65 }66 },67 "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],68 "exclude": ["node_modules"]69}70```7172> **Note:** do not forget to remove all comments from your `tsconfig.json` file.7374### Initializing the store7576```ts77// src/stores/counter-store.ts78import { createStore } from 'zustand/vanilla'7980export type CounterState = {81 count: number82}8384export type CounterActions = {85 decrementCount: () => void86 incrementCount: () => void87}88

Change CounterStore type from intersection to union (#3565)Danilo Brittobefore adoptionb126c33

line 89why, one step back
89export type CounterStore = CounterState | CounterActions

Revamping docs - file restructuring (#3392)Danilo Brittobefore adoption8eae4e9

lines 90–316why, one step back
90
91export const defaultInitState: CounterState = {92 count: 0,93}9495export const createCounterStore = (96 initState: CounterState = defaultInitState,97) => {98 return createStore<CounterStore>()((set) => ({99 ...initState,100 decrementCount: () => set((state) => ({ count: state.count - 1 })),101 incrementCount: () => set((state) => ({ count: state.count + 1 })),102 }))103}104```105106### Providing the store107108Let's use the `createCounterStore` in our component and share it using a context provider.109110```tsx111// src/providers/counter-store-provider.tsx112'use client'113114import { type ReactNode, createContext, useState, useContext } from 'react'115import { useStore } from 'zustand'116117import { type CounterStore, createCounterStore } from '@/stores/counter-store'118119export type CounterStoreApi = ReturnType<typeof createCounterStore>120121export const CounterStoreContext = createContext<CounterStoreApi | undefined>(122 undefined,123)124125export interface CounterStoreProviderProps {126 children: ReactNode127}128129export const CounterStoreProvider = ({130 children,131}: CounterStoreProviderProps) => {132 const [store] = useState(() => createCounterStore())133 return (134 <CounterStoreContext.Provider value={store}>135 {children}136 </CounterStoreContext.Provider>137 )138}139140export const useCounterStore = <T,>(141 selector: (store: CounterStore) => T,142): T => {143 const counterStoreContext = useContext(CounterStoreContext)144 if (!counterStoreContext) {145 throw new Error(`useCounterStore must be used within CounterStoreProvider`)146 }147148 return useStore(counterStoreContext, selector)149}150```151152> **Note:** In this example, we ensure that this component is re-render-safe by checking the153> value of the reference, so that the store is only created once. This component will only be154> rendered once per request on the server, but might be re-rendered multiple times on the client if155> there are stateful client components located above this component in the tree, or if this component156> also contains other mutable state that causes a re-render.157158### Using the store with different architectures159160There are two architectures for a Next.js application: the161[Pages Router](https://nextjs.org/docs/pages/building-your-application/routing) and the162[App Router](https://nextjs.org/docs/app/building-your-application/routing). The usage of Zustand on163both architectures should be the same with slight differences related to each architecture.164165#### Pages Router166167```tsx168// src/components/pages/home-page.tsx169import { useCounterStore } from '@/providers/counter-store-provider'170171export const HomePage = () => {172 const { count, incrementCount, decrementCount } = useCounterStore(173 (state) => state,174 )175176 return (177 <div>178 Count: {count}179 <hr />180 <button type="button" onClick={incrementCount}>181 Increment Count182 </button>183 <button type="button" onClick={decrementCount}>184 Decrement Count185 </button>186 </div>187 )188}189```190191```tsx192// src/_app.tsx193import type { AppProps } from 'next/app'194195import { CounterStoreProvider } from '@/providers/counter-store-provider'196197export default function App({ Component, pageProps }: AppProps) {198 return (199 <CounterStoreProvider>200 <Component {...pageProps} />201 </CounterStoreProvider>202 )203}204```205206```tsx207// src/pages/index.tsx208import { HomePage } from '@/components/pages/home-page'209210export default function Home() {211 return <HomePage />212}213```214215> **Note:** creating a store per route would require creating and sharing the store216> at page (route) component level. Try not to use this if you do not need to create217> a store per route.218219```tsx220// src/pages/index.tsx221import { CounterStoreProvider } from '@/providers/counter-store-provider'222import { HomePage } from '@/components/pages/home-page'223224export default function Home() {225 return (226 <CounterStoreProvider>227 <HomePage />228 </CounterStoreProvider>229 )230}231```232233#### App Router234235```tsx236// src/components/pages/home-page.tsx237'use client'238239import { useCounterStore } from '@/providers/counter-store-provider'240241export const HomePage = () => {242 const { count, incrementCount, decrementCount } = useCounterStore(243 (state) => state,244 )245246 return (247 <div>248 Count: {count}249 <hr />250 <button type="button" onClick={incrementCount}>251 Increment Count252 </button>253 <button type="button" onClick={decrementCount}>254 Decrement Count255 </button>256 </div>257 )258}259```260261```tsx262// src/app/layout.tsx263import type { Metadata } from 'next'264import { Inter } from 'next/font/google'265import './globals.css'266267import { CounterStoreProvider } from '@/providers/counter-store-provider'268269const inter = Inter({ subsets: ['latin'] })270271export const metadata: Metadata = {272 title: 'Create Next App',273 description: 'Generated by create next app',274}275276export default function RootLayout({277 children,278}: Readonly<{279 children: React.ReactNode280}>) {281 return (282 <html lang="en">283 <body className={inter.className}>284 <CounterStoreProvider>{children}</CounterStoreProvider>285 </body>286 </html>287 )288}289```290291```tsx292// src/app/page.tsx293import { HomePage } from '@/components/pages/home-page'294295export default function Home() {296 return <HomePage />297}298```299300> **Note:** creating a store per route would require creating and sharing the store301> at page (route) component level. Try not to use this if you do not need to create302> a store per route.303304```tsx305// src/app/page.tsx306import { CounterStoreProvider } from '@/providers/counter-store-provider'307import { HomePage } from '@/components/pages/home-page'308309export default function Home() {310 return (311 <CounterStoreProvider>312 <HomePage />313 </CounterStoreProvider>314 )315}316```