# zustand

Goal: zustand in a React app, with a store made for each request and its server-set state in the browser at hydration. The runnable sample is `examples/data-react/`; `zustand` is a devDependency of that example, and Hamur has no module for it.

When Hamur's own state is enough: `useState(key, init)` is state shared by key that travels with the page ([State](/state)). Reach for zustand when the state is a store with its own actions and selectors, or already is one. The two work together.

1. Do not use `create()` at module level. A store made when the module loads lives as long as the server and is shared by every request. Make it in an app plugin with `createStore` from `zustand/vanilla`, which runs for each request, and hand it to components with `provide`. `useHydration(app, key, get, set)` puts its data in the page payload after the render and gives it back in the browser when the plugin runs ([Handing a value from the server to the browser](/state#handing-a-value-from-the-server-to-the-browser)):

````ts [examples/data-react/app/plugins/cart.ts]
import { definePlugin, useHydration } from "hamur/app"
import { createStore } from "zustand/vanilla"

export interface CartState {
  items: string[]
  servedAt: string
  add(item: string): void
}

type CartData = Pick<CartState, "items" | "servedAt">

export default definePlugin((app) => {
  let seed: CartData = { items: [], servedAt: app.event ? new Date().toISOString() : "" }
  useHydration(
    app,
    "cart",
    (): CartData => ({ items: cart.getState().items, servedAt: cart.getState().servedAt }),
    (value) => {
      seed = value
    },
  )
  const cart = createStore<CartState>((set) => ({
    ...seed,
    add: (item) => set((state) => ({ items: [...state.items, item] })),
  }))
  return { provide: { cart } }
})
````

Hydration sets the starting state of the store, not the store after it exists. zustand's `useStore` reads `getInitialState()` while React hydrates, so a value written later with `setState` would not match the server's HTML. The plugin takes the payload's value first (`set` runs while `useHydration` is called in the browser) and builds the store from it. Only data is stored: functions such as `add` are not serializable, so `get` returns the data fields alone.

2. Read it in a component. `useApp()` returns the context with the plugin's `provide` keys, typed by `hamur typegen`. Pass the store to `useStore` with a selector:

````tsx [examples/data-react/app/pages/zustand.tsx]
import { useApp } from "@hamur/adapter-react"
import { useStore } from "zustand"

export default function Cart() {
  const { cart } = useApp()
  const items = useStore(cart, (state) => state.items)
  const servedAt = useStore(cart, (state) => state.servedAt)

  return (
    <main>
      <h1>zustand</h1>
      <p>Served at {servedAt}</p>
      <ul>
        {items.map((item, at) => (
          <li key={at}>{item}</li>
        ))}
      </ul>
      <button onClick={() => cart.getState().add(`Item ${items.length + 1}`)}>Add</button>
    </main>
  )
}
````

`servedAt` was set by the server and is in the store from the first render. `add` changes the store in the browser; a reload starts from the server's state again.

3. Keep it small. A store that holds what a handler returns duplicates `useData` and `useAsyncData`, and then two copies can differ. Keep server data in `load` and handlers, and put in the store what only the browser decides, such as a cart in progress or a panel's state.

See also: [State](/state), [Plugins and hooks](/plugins-and-hooks), [Hydration](/recipes/hydration), [TanStack Query](/recipes/tanstack-query).
