Skip to content
D
Documentation

Server-render React stores

how-to
5 min readUpdated

Use a request-scoped store when you render React on a server. These examples render Count: 7 as HTML, then hydrate it so the increment and decrement buttons update the count in the browser.

For server rendering, create a separate instance per request with createStore and consume that instance with useStore; see Stores and React bindings for the general API relationship, including create.

Start from the React quick start for the standalone HTTP server. The Next.js section uses a separate App Router project. Neither example imports the quick start's global counter store.

Creating a store per request

  1. Add a factory instead of exporting a live store. Each call returns a new store containing the supplied count and its actions.

    The data and actions form an intersection: a counter has both. Only the data travels from server to browser; each side creates its own action functions.

ts
import { createStore } from 'zustand/vanilla'

export type CounterState = { count: number }
export type CounterActions = {
  incrementCount: () => void
  decrementCount: () => void
}
export type CounterStore = CounterState & CounterActions

export function createCounterStore(initialState: CounterState) {
  return createStore<CounterStore>()((set) => ({
    ...initialState,
    incrementCount: () => set((state) => ({ count: state.count + 1 })),
    decrementCount: () => set((state) => ({ count: state.count - 1 })),
  }))
}
  1. Provide the instance through context. The lazy useState initializer retains the client instance across re-renders. On the server, the provider belongs to the request's render tree, not to shared module state.
tsx
import { createContext, useContext, useState } from 'react'
import type { ReactNode } from 'react'
import { useStore } from 'zustand'
import { createCounterStore } from './counter-store'
import type { CounterState, CounterStore } from './counter-store'

export const CounterStoreContext = createContext<
  ReturnType<typeof createCounterStore> | undefined
>(undefined)

export function CounterStoreProvider({
  initialState,
  children,
}: {
  initialState: CounterState
  children: ReactNode
}) {
  const [store] = useState(() => createCounterStore(initialState))
  return (
    <CounterStoreContext.Provider value={store}>
      {children}
    </CounterStoreContext.Provider>
  )
}

export function useCounterStore<T>(selector: (state: CounterStore) => T): T {
  const store = useContext(CounterStoreContext)
  if (!store) {
    throw new Error('useCounterStore requires a CounterStoreProvider')
  }
  return useStore(store, selector)
}

export function Counter() {
  const count = useCounterStore((state) => state.count)
  const increment = useCounterStore((state) => state.incrementCount)
  const decrement = useCounterStore((state) => state.decrementCount)

  return (
    <main style={{ minHeight: 400, padding: 24 }}>
      <h1>Server-rendered counter</h1>
      <p aria-live="polite">Count: {count}</p>
      <button type="button" onClick={increment}>Increment Count</button>
      <button type="button" onClick={decrement}>Decrement Count</button>
    </main>
  )
}

export default function ServerCounter() {
  return (
    <CounterStoreProvider initialState={{ count: 7 }}>
      <Counter />
    </CounterStoreProvider>
  )
}

The included Counter selects the count and each action separately. Clicking either button changes the displayed number without a refresh call. ServerCounter composes the provider and consumer; the HTTP entries below mount the consumer with their request's instance instead.

The counter displays Count: 7 with Increment Count and Decrement Count buttons.

The provider supplies an instance, not a second state container. useStore subscribes to that instance, reads getState() for client updates, and reads getInitialState() for the server and hydration snapshot.

Render with Next.js App Router

Next.js transports the initial data and hydrates the Client Components for you. Keep the store inside the Client Component provider; the Server Component passes data without reading or writing a Zustand store.

  1. Create a TypeScript App Router project. This project is separate from the Vite project in the React quick start.
bash
npx create-next-app@latest zustand-next --ts --app --use-npm --yes
cd zustand-next
npm install zustand
  1. Add a Client Component containing the store factory, provider, and consumer. Leave the starter's layout, fonts, global stylesheet, and TypeScript configuration intact. This is the same per-request pattern as the standalone example, contained within a client boundary.
tsx
'use client'

import { createContext, useContext, useState } from 'react'
import { createStore, useStore } from 'zustand'

type CounterStore = {
  count: number
  incrementCount: () => void
  decrementCount: () => void
}

function createCounterStore(count: number) {
  return createStore<CounterStore>()((set) => ({
    count,
    incrementCount: () => set((state) => ({ count: state.count + 1 })),
    decrementCount: () => set((state) => ({ count: state.count - 1 })),
  }))
}

const CounterContext = createContext<
  ReturnType<typeof createCounterStore> | undefined
>(undefined)

function Counter() {
  const store = useContext(CounterContext)
  if (!store) throw new Error('Counter requires a provider')
  const count = useStore(store, (state) => state.count)
  const increment = useStore(store, (state) => state.incrementCount)
  const decrement = useStore(store, (state) => state.decrementCount)

  return (
    <main style={{ minHeight: 400, padding: 24 }}>
      <h1>Server-rendered counter</h1>
      <p aria-live="polite">Count: {count}</p>
      <button type="button" onClick={increment}>Increment Count</button>
      <button type="button" onClick={decrement}>Decrement Count</button>
    </main>
  )
}

export default function NextCounter({ initialCount = 7 }: { initialCount?: number }) {
  const [store] = useState(() => createCounterStore(initialCount))
  return (
    <CounterContext.Provider value={store}>
      <Counter />
    </CounterContext.Provider>
  )
}

The counter component renders a “Server-rendered counter” heading, Count: 7, and Increment Count and Decrement Count buttons.

Add the route beside that component rather than replacing the starter's home page. If your starter uses src/app, put both files there instead of creating a second app directory.

tsx
import { Suspense } from 'react'
import { connection } from 'next/server'
import NextCounter from './NextCounter'

async function RequestCounter() {
  await connection()
  return <NextCounter initialCount={7} />
}

export default function CounterPage() {
  return (
    <Suspense fallback={<p>Loading counter…</p>}>
      <RequestCounter />
    </Suspense>
  )
}

connection() makes the counter request-rendered. The Suspense boundary supplies a fallback while that request-dependent subtree waits. Replace the literal count with your request's data when integrating the page. Pass the resulting data to the provider; do not compute a different initial count inside the browser's provider.

  1. Build and run the application.
bash
npm run build
npm run dev

Open /counter on the local server. The initial HTML contains Count: 7. After hydration, Increment Count changes it to Count: 8, and Decrement Count subtracts one. A separate browser session receives a separate initial store.

Choose the provider's lifetime

A provider in a shared layout can retain its store during client navigation. Place it around the existing {children} in that layout when its state belongs to the whole subtree; preserve the layout's other markup and imports. Place it at a route boundary when the state belongs to that route. A newly mounted provider creates a new store; changing initialState on an already mounted provider does not replace the existing store.

For a Pages Router application, place the provider in your existing _app.tsx, around its existing <Component {...pageProps} />, for application-wide scope, or in a page for route scope. Preserve that entry's other wiring. Use the same request data to initialize both renders; do not add a second /counter page alongside the App Router example.

Render and hydrate with a standalone HTTP server

Here you supply the pieces Next.js supplies: Express handles requests, renderToPipeableStream renders HTML, and hydrateRoot attaches React to the existing markup. The server creates its store inside the request handler and sends only the initial count to the browser.

Use the Vite project left by the React quick start. Add src/ssr/counter-store.ts and src/ssr/counter-provider.tsx from the first section. Keep its existing src/main.tsx, stylesheet, Vite configuration, and TypeScript project references; the SSR example has a separate entry and type-check configuration.

  1. Install the HTTP server and build tools. React, React DOM, TypeScript, their types, and Zustand are already installed by the quick start.
bash
npm install express
npm install -D @types/express @types/node tsx esbuild
  1. Add a complete ssr/tsconfig.json for checking the server, client entry, and shared counter files. It does not replace the starter's root tsconfig.json.
json
{
  "compilerOptions": {
    "target": "ES2022",
    "lib": ["ES2022", "DOM", "DOM.Iterable"],
    "module": "ESNext",
    "moduleResolution": "Bundler",
    "jsx": "react-jsx",
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noPropertyAccessFromIndexSignature": true,
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "noEmit": true,
    "types": ["node"]
  },
  "include": ["./**/*.tsx", "../src/ssr/**/*.ts", "../src/ssr/**/*.tsx"]
}
  1. Add the server. getInitialState() returns the store's creation-time snapshot. Extract the data field from that snapshot so action functions never enter the serialized payload.
tsx
import express from 'express'
import process from 'node:process'
import { StrictMode } from 'react'
import { renderToPipeableStream } from 'react-dom/server'
import { Counter, CounterStoreContext } from '../src/ssr/counter-provider'
import { createCounterStore } from '../src/ssr/counter-store'

const app = express()
const port = Number.parseInt(process.env['PORT'] ?? '3000', 10)

app.use('/assets', express.static('dist-ssr'))

app.get('/', (_request: typeof express.request, response: typeof express.response) => {
  const store = createCounterStore({ count: 7 })
  const initialState = { count: store.getInitialState().count }
  const payload = JSON.stringify(initialState).replace(/</g, '\\u003c')

  const { pipe } = renderToPipeableStream(
    <html lang="en">
      <head>
        <meta charSet="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Server-rendered counter</title>
      </head>
      <body>
        <div id="ssr-root">
          <StrictMode>
            <CounterStoreContext.Provider value={store}>
              <Counter />
            </CounterStoreContext.Provider>
          </StrictMode>
        </div>
        <script
          id="initial-state"
          type="application/json"
          dangerouslySetInnerHTML={{ __html: payload }}
        />
      </body>
    </html>,
    {
      bootstrapScripts: ['/assets/client.js'],
      onShellReady() {
        response.setHeader('content-type', 'text/html; charset=utf-8')
        pipe(response)
      },
      onShellError(error) {
        console.error(error)
        response.statusCode = 500
        response.end('Unable to render the counter')
      },
      onError(error) {
        console.error(error)
      },
    },
  )
})

app.listen(port, () => {
  console.log(`Open http://localhost:${port}`)
})

The JSON script carries data without executing it. Escaping < prevents a serialized value from terminating the script element. The client bundle is served before the page route, so a script request receives JavaScript rather than another HTML render.

  1. Add the browser entry. It reads the payload once, validates the count, creates one client store, and hydrates the same counter tree. It does not call createRoot, which is for a root without server-rendered content.
tsx
import { StrictMode } from 'react'
import { hydrateRoot } from 'react-dom/client'
import { Counter, CounterStoreContext } from './counter-provider'
import { createCounterStore } from './counter-store'
import type { CounterState } from './counter-store'

const root = document.getElementById('ssr-root')
const payload = document.getElementById('initial-state')?.textContent
if (!root || !payload) {
  throw new Error('Missing server-rendered root or initial state')
}

const parsed: CounterState = JSON.parse(payload)
if (!parsed || typeof parsed.count !== 'number' || !Number.isFinite(parsed.count)) {
  throw new Error('Invalid initial counter state')
}
const store = createCounterStore({ count: parsed.count })

hydrateRoot(
  root,
  <StrictMode>
    <CounterStoreContext.Provider value={store}>
      <Counter />
    </CounterStoreContext.Provider>
  </StrictMode>,
)
  1. Check the files, bundle the browser entry, and start the server from the project root.
bash
npm run build
npx tsc -p ssr/tsconfig.json
npx esbuild src/ssr/client.tsx --bundle --platform=browser --format=iife --outfile=dist-ssr/client.js
npx tsx ssr/server.tsx

Open http://localhost:3000. You see the heading, Count: 7, and both buttons. The server HTML already contains the number; the downloaded bundle makes the buttons interactive. Reloading makes a new request and a new store starting at seven.

Initialization and scope options

These are the inputs to the example's provider, not additional Zustand configuration.

OptionTypeDefaultWhat it does
initialStateCounterStateRequiredSupplies the count when the provider creates its store.
childrenReactNodeRequiredSupplies the components that consume this store through context.

useStore(store, selector) returns the selected value. Omitting the selector returns the whole state. The examples select individual fields so each subscription describes what its component needs.

Keep hydration consistent

  • Do not export a global store from a Next.js server module. Concurrent requests can share that module's state. Export the factory and create the instance within the request's render scope instead.
  • Initialize the server and client with identical data. Do not choose initial state independently with the current time or browser storage. Different output causes hydration errors.
  • Do not read or write the store from React Server Components. Pass serializable data to the Client Component provider instead.
  • Retain the client instance across re-renders. The lazy initializer is not a mechanism for applying later prop changes; remount deliberately when you need a new scope.
  • Hydrate the same React tree without injecting extra whitespace inside its root or rendering different branches based on browser-only APIs.

For provider placement beyond server rendering, see Scope stores with context. For storage-backed state after the initial render, see Control state hydration; persistence hydration is separate from React attaching to server HTML.

Was this page helpful?