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). Reach for zustand when the state is a store with its own actions and selectors, or already is one. The two work together.
- 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 withcreateStorefromzustand/vanilla, which runs for each request, and hand it to components withprovide.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):
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.
- Read it in a component.
useApp()returns the context with the plugin'sprovidekeys, typed byhamur typegen. Pass the store touseStorewith a selector:
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.
- Keep it small. A store that holds what a handler returns duplicates
useDataanduseAsyncData, and then two copies can differ. Keep server data inloadand 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, Plugins and hooks, Hydration, TanStack Query.