State: choosing where a value lives
On this page
- Server HTML and islands
- Local state: useState
- Shared values: useShared
- The __bpShared contract
- SIR interop
- The cart: useCart and useCartActions
- Cart view: useCartView
- The shopper and the wishlist
- Sign-in and sign-up: useCustomerAuth
- SIR events
- Worked example: size picker, live price and add to cart
- Patterns
- Anti-patterns
A storefront page holds two kinds of state: what the page shows to everyone (server HTML), and what
one shopper does with it (browser state). This page helps you pick the right tool for each value, from
a plain useState in one island to the cart, the signed-in shopper and values shared across islands.
The short answer:
| The value is... | Use | Where it lives |
|---|---|---|
| the same for every shopper (a product, a price, a menu) | data() and render() |
the server HTML |
| used by one island only (an open menu, a quantity, a tab) | useState |
that island |
| followed by several islands (the chosen size) | useShared(key, initial) |
globalThis.__bpShared, for this page |
| the cart | useCart() and useCartActions() |
the storefront host |
| a full cart page (lines, quantities, free shipping) | useCartView() |
the storefront host, shown at once |
| the signed-in shopper | useCustomer() |
the storefront host |
| signing in, signing up, signing out | useCustomerAuth() |
the storefront host |
| the wishlist | useWishlist() |
the storefront host |
| data that arrives after a click or a keystroke | useQuery() |
an in-memory cache for the visit |
| a filter, a sort or a page number | a link with a query string (?sort=price) |
the URL |
Every hook on this page comes from @bizzpocket/theme/client and works only inside an island (a
'use client' file). interactivity.md explains islands themselves.
Server HTML and islands
The storefront renders each page once, on the server, and the page is the same for every shopper.
It holds no cart, no name and no wishlist. That is what lets the storefront and its CDN cache the HTML
and send the same copy to everyone. On the Bun storefront, for example, a normal page is sent with
cache-control: public, s-maxage=60, stale-while-revalidate=600.
The personal part is filled in later, in the browser:
- The server renders your block, islands included, with their props.
- The browser shows that HTML at once. No JavaScript has run yet.
- An island wakes up (its block's
hydratesetting decides when). React takes over the island's HTML. - The island's hooks ask the storefront host for the cart, the shopper or the wishlist, and render again when the answer arrives.
So in the server render, and in the first render in the browser, the hooks have no answer yet:
| Hook | First render (server and browser) | After the host answers |
|---|---|---|
useCart() |
{ cart: null, count: 0, ready: false } |
the cart, ready: true |
useCustomer() |
{ customer: null, ready: false } |
the shopper, or null for a guest; ready: true |
useWishlist() |
{ productIds: [], count: 0, ready: false } |
the ids, ready: true |
useShared(key, initial) |
initial |
the page's current value |
useQuery(...) |
loading: true, data: undefined |
the result |
Render something sensible for that first moment, and keep its size the same as the final state, so the
page does not jump. A "Hello, Asha" that replaces an empty <span> of the same height is fine. A banner
that appears and pushes the page down is not.
Note. A block with load() can break this rule on purpose: load() runs per request, and its
customer* operations run as the shopper. When one ran, the page is sent private, no-store and is not
cached, with or without a cookie. Public operations go without the cookie and keep the page cached. See
limits.md. Prefer the hooks for anything personal.
Local state: useState
A value that only one island uses belongs in that island, with React's own useState. Nothing else is
needed: no store, no key, no event.
'use client';
import { useState } from 'react';
export function SizeGuideToggle({ label, text }: { label: string; text: string }) {
const [open, setOpen] = useState(false);
return (
<div>
<button type="button" aria-expanded={open} aria-controls="size-guide" onClick={() => setOpen(!open)}>
{label}
</button>
<p id="size-guide" hidden={!open}>
{text}
</p>
</div>
);
}And the block, blocks/size-guide/size-guide.tsx:
import { block, f } from '@bizzpocket/theme';
import { SizeGuideToggle } from './size-guide-toggle';
export default block({
name: 'Size guide',
category: 'content',
fields: {
label: f.text({ default: 'Size guide' }),
text: f.text({ multiline: true, default: 'Measure around the widest part of your knuckle.' }),
},
render: ({ label, text }) => <SizeGuideToggle label={label} text={text} />,
});Local state starts again from its initial value on every page load. It is not kept when the shopper moves to another page.
Shared values: useShared
Islands are bundled separately and do not share React context, so two islands cannot share a
useState. When several islands follow one value, use useShared(key, initial). It returns
[value, set], like useState, and every island that uses the same key sees the same value.
const [size, setSize] = useShared<string | null>(`size:${productId}`, null);- The first render shows
initial. Right after the island wakes up it reads the value already on the page (set by another island or by SIR), then follows every change. set(next)orset((prev) => next)changes it for every island at once. Setting the value it already has does nothing.- Values live for the page only. Leaving the page forgets them.
- Prefix keys with what they belong to (
size:<productId>), so two products on one page do not clash. - Keep values plain data. A function passed to
setis treated as an updater, so the value itself cannot be a function.
The __bpShared contract
useShared is a thin layer over a page-wide convention that any script can use:
-
The store is
globalThis.__bpShared, aMap<string, unknown>. Whoever writes first creates it. -
A change is announced on
windowas the eventbizzpocket:shared:<key>, with the new value as itsdetail. -
To write a value, set it in the map, then send the event:
tsconst store = ((globalThis as any).__bpShared ??= new Map()); store.set(key, value); window.dispatchEvent(new CustomEvent(`bizzpocket:shared:${key}`, { detail: value })); -
Outside React,
getShared(key),setShared(key, value)andsubscribeShared(key, listener)do the same.subscribeSharedreturns the function that stops listening. -
On the server,
setShareddoes nothing: the server'sglobalThisis shared by every request, so nothing may be stored there.
SIR interop
SIR's variant picker writes the key variant:<productId>. Its
value is { productId, variantId, variant }:
variantis the row of the variant table that is chosen, ornull.variantIdisnullwhen the chosen options match no variant.- The picker sets the key for its opening state too, so an island that wakes up later still reads it.
So an island can follow the shopper's choice with no props from the picker:
const [choice] = useShared<{ variantId: string | null } | null>(`variant:${productId}`, null);The picker also fires bizzpocket:variant:change with the same object on every pick (not for the
opening state). The worked example below uses it.
The cart: useCart and useCartActions
The cart belongs to the storefront host, not to your theme. Your islands read it and ask for changes.
- Read it with
useCart():{ cart, count, ready }.cart.itemsholds the lines (id,productId,quantity,unitPrice,lineTotal...), andcart.totalsthe subtotal and total. - Change it with
useCartActions():add(...),update(lineId, quantity)andremove(lineId)return Promises, andpendinganderrorare React state for your button.
const { count, ready } = useCart();
const { add, pending, error } = useCartActions();An add resolves with the updated cart or rejects with { code, message }. code is the store's own
reason (OUT_OF_STOCK, VARIANT_REQUIRED...) or TIMEOUT after 15 seconds.
interactivity.md has the full table.
Do not copy the cart into your own state. Every island that calls useCart() follows the host's
bizzpocket:cart:updated event, so they all show the same cart.
Cart view: useCartView
useCart() gives you the host's cart. A cart page needs more: a quantity box that answers at once,
a remove button, free-shipping progress and a sentence for screen readers. useCartView() does all of
that, so you do not write the event code yourself. Your theme keeps the markup, the coupon box and the
breadcrumbs.
'use client';
import { useCartView } from '@bizzpocket/theme/client';
export function CartView({ initialCart, freeShippingOver }) {
const cart = useCartView(initialCart, { freeShippingOver });
if (cart.empty) return <p role="status">{cart.liveMessage || 'Your cart is empty.'}</p>;
return (
<>
<p aria-live="polite" className="sr-only">{cart.liveMessage}</p>
{cart.error ? <p role="alert">{cart.error.message}</p> : null}
<ul>
{cart.lines.map((line) => (
<li key={line.lineId}>
<a href={line.href}>{line.title}</a>
<input
type="number"
min={0}
value={line.quantity}
disabled={cart.pending.has(line.lineId)}
onChange={(e) => cart.setQuantity(line.lineId, e.currentTarget.valueAsNumber)}
/>
<button type="button" disabled={cart.pending.has(line.lineId)} onClick={() => cart.remove(line.lineId)}>
Remove
</button>
</li>
))}
</ul>
</>
);
}initialCart is the { lines, totals } your block rendered on the server: declare it with
initialCart: f.cart(). On the storefront the cart is server-rendered into this prop on the
cart page. On the Bun renderer and on other pages the prop is empty and the island receives the cart from the cart event,
so render an empty-until-synced state (initialCart ?? { lines: [] }). useCartView takes locale (the page's
ctx.locale) and a messages.updated that may be a forms object for a language
with more than two plural forms. The hook sends no request on mount. After a change it follows the host's bizzpocket:cart:synced and bizzpocket:cart:error events.
What it returns:
| Member | Meaning |
|---|---|
lines |
The lines, each with an href to the product. |
totals |
The host's totals (subtotal, total, discountAmount...), or undefined. |
empty, itemCount, lineCount |
lineCount counts lines. itemCount adds the quantities. |
pending |
A Set of line ids whose change the host has not confirmed. Disable their controls. |
setQuantity(lineId, quantity) |
Sets a quantity. Below 1 removes the line. A value that is not a whole number or not finite is ignored. |
remove(lineId) |
Removes a line. |
freeShipping |
{ remaining, pct, reached, currency }, or null without freeShippingOver (or with mixed currencies). |
liveMessage |
Text for an aria-live="polite" region. It is empty until the cart first changes, so nothing is read out on page load. |
error |
{ lineId, message } for the last failed change, else null. |
States. On load the cart is initialCart. When the shopper changes a line, the hook shows the change at
once (optimistic), adds the id to pending, and sends the change to the host. The host's next
cart:synced replaces the lines and clears pending and error. If the host sends cart:error, the
line goes back to its last confirmed state, leaves pending, and error holds the message. The next
action or sync clears error. While a change is waiting, the subtotal is worked out from the lines.
Options (second argument):
| Option | Default | Meaning |
|---|---|---|
freeShippingOver |
none | The store's threshold. |
messages |
English | The liveMessage sentences: empty, updated, freeShippingRemaining, freeShippingReached. Each is a template with {name} values, or a function. |
pctRounding |
'floor-until-reached' |
'round' rounds freeShipping.pct to the nearest percent, so it can show 100 a moment before the threshold is met. |
const cart = useCartView(initialCart, {
freeShippingOver: 1499,
messages: { freeShippingRemaining: 'Add {remaining} more for free shipping.' },
pctRounding: 'round',
});Extra line fields. A theme that adds its own fields to a line types them with a type argument. The
fields stay on lines and in the optimistic updates:
import type { CartInput } from '@bizzpocket/theme/kit';
const initial: CartInput<{ gift: boolean }> = { lines: giftLines, totals };
const cart = useCartView(initial);
cart.lines[0]?.gift; // booleanThe same logic without the hook is cartModel in kit.md. Use it to render the
cart on the server.
The shopper and the wishlist
useCustomer()returns{ customer, ready }.customeris{ id, email?, firstName?, lastName?, name?, phone? }, ornullfor a guest.useWishlist()returns{ productIds, has(productId), count, ready }. It also followsbizzpocket:wishlist:toggle, so a heart elsewhere on the page updates it at once.
Wait for ready before you decide the shopper is a guest:
'use client';
import { useCustomer } from '@bizzpocket/theme/client';
export function AccountLink() {
const { customer, ready } = useCustomer();
// Same box before and after the answer, so nothing moves.
if (!ready) return <a href="/account">Account</a>;
if (customer === null) return <a href="/account/login">Sign in</a>;
return <a href="/account">Hi, {customer.firstName ?? customer.name ?? 'there'}</a>;
}And the block, blocks/account-link/account-link.tsx:
import { block } from '@bizzpocket/theme';
import { AccountLink } from './account-link-island';
export default block({
name: 'Account link',
category: 'header',
hydrate: 'load',
render: () => <AccountLink />,
});The shopper's data never reaches the server HTML, so the page stays cacheable.
Sign-in and sign-up: useCustomerAuth
useCustomerAuth() runs the account forms of an island: password sign-in, one-time code, sign-up,
password reset and sign-out. You write the form. The hook sends the request, with no copied transport
file and no raw fetch.
'use client';
import { useCustomerAuth } from '@bizzpocket/theme/client';
export function LoginForm({ storeSlug }: { storeSlug: string }) {
const auth = useCustomerAuth({ storeSlug });
return (
<form
onSubmit={(e) => {
e.preventDefault();
const f = new FormData(e.currentTarget);
auth.signIn({ identifier: String(f.get('identifier')), password: String(f.get('password')) }).catch(() => {});
}}
>
<input name="identifier" autoComplete="username" />
<input name="password" type="password" autoComplete="current-password" />
{auth.error ? <p role="alert">{auth.error.message}</p> : null}
<button type="submit" disabled={auth.pending}>Sign in</button>
</form>
);
}State: pending is true while a request runs, and error is the last failure ({ code, message, status?, attemptsLeft? }), cleared when the next action starts. clearError() clears it by hand. The message is
safe to show. It never holds a password, a code or a token.
Actions. Each returns a Promise that rejects with the same error object, so it also works with
useForm:
| Action | What it does |
|---|---|
signIn({ identifier, password }) |
Password sign-in. |
requestOtp({ identifier }) |
Sends a one-time code (step 1). |
verifyOtp({ identifier, otp }) |
Signs in with the code (step 2). Wrong codes fail with INVALID_OTP and attemptsLeft. |
signUp(input, { signIn? }) |
Makes an account from an email, a phone, or both, with an optional password, firstName and lastName. By default it then signs in. With no password it sends a code instead, and verifyOtp finishes. The result is { customerId, signedIn, signInError? }. |
requestPasswordReset({ identifier }) |
Sends the reset code. Never navigates. |
resetPassword({ identifier, otp, newPassword }) |
Sets the new password. Never navigates and does not sign in: show the sign-in form next. |
signOut() |
Ends the session. |
Options: storeSlug (pass the block's ctx.store.slug. On a custom domain without it the request fails with VALIDATION_ERROR), timeoutMs (default
15 seconds), redirect and signOutRedirect. After a sign-in the hook loads ?next= (checked with
safeNextPath) or redirect (default /account). Use redirect: false to stay on the page.
useCustomer() updates either way. After sign-out it loads signOutRedirect (default /account/login).
Rules the hook keeps for you:
- One request per action at a time, page-wide. A double submit never sends twice. The second call rejects
with
BUSY. - A request is aborted when the island unmounts.
- A password shorter than 10 characters is refused as
WEAK_PASSWORDbefore anything is sent.
Common error codes: INVALID_CREDENTIALS, ACCOUNT_LOCKED, INVALID_OTP, OTP_EXPIRED,
RATE_LIMITED, ALREADY_EXISTS, WEAK_PASSWORD, VALIDATION_ERROR, CSRF_FAILED, NETWORK_ERROR,
TIMEOUT. Show error.message. Switch on error.code only when the wording or the next step differs.
The same actions exist as plain functions (signIn, requestOtp, verifyOtp, signUp, signOut,
requestPasswordReset, resetPassword) for code that is not a React component. createCustomerAuth
builds the hook's controller for a non-React island.
SIR events
The hooks are built on browser events dispatched on window. You rarely need them directly, but they
are the contract between your theme and every storefront host. Names and detail shapes come from
@bizzpocket/sir/contract.
| Event | Direction | detail |
Used by |
|---|---|---|---|
bizzpocket:cart:request |
theme → host | none | useCart() on mount: "tell me the cart" |
bizzpocket:cart:updated |
host → theme | the cart: { items, itemCount?, currency?, totals? } |
useCart(), cart actions |
bizzpocket:cart:add |
theme → host | { productId, variantId?, quantity, handle?, attributes? } |
sir.addToCart, add() |
bizzpocket:cart:update |
theme → host | { lineId, quantity } |
update() |
bizzpocket:cart:remove |
theme → host | { lineId } |
remove() |
bizzpocket:cart:error |
host → theme | { productId, variantId?, lineId?, code, message } (a failed update or remove carries lineId and productId: '') |
cart actions (reject) |
bizzpocket:cart:open |
theme → host | none | sir.cartDrawer; the host opens its cart drawer |
bizzpocket:cart:synced |
host → theme | { lines, totals } (the cart block's shape) |
theme cart blocks |
bizzpocket:customer:request |
theme → host | none | useCustomer() on mount |
bizzpocket:customer:updated |
host → theme | { id, email?, firstName?, lastName?, name?, phone? } or null |
useCustomer() |
bizzpocket:wishlist:request |
theme → host | none | useWishlist() on mount |
bizzpocket:wishlist:updated |
host → theme | { productIds } |
useWishlist() |
bizzpocket:wishlist:toggle |
theme → host | { productId, wished } |
sir.wishlistToggle, useWishlist() |
bizzpocket:wishlist:remove |
theme → host | { productId } |
theme wishlist grids |
bizzpocket:profile:save |
theme → host | { name, email, phone, currentPassword?, newPassword?, confirmPassword? } |
theme account blocks |
bizzpocket:address:save |
theme → host | { address } (with _delete: true to delete) |
theme account blocks |
bizzpocket:review:submit |
theme → host | { productId, rating, comment?, ... } |
theme product pages |
bizzpocket:account:saved |
host → theme | { kind } ('profile', 'address-add', 'review'...) |
theme account blocks |
bizzpocket:account:error |
host → theme | { kind, message } |
theme account blocks |
bizzpocket:variant:change |
SIR → page | { productId, variantId, variant } |
anything that follows the variant picker |
bizzpocket:shared:<key> |
anyone → page | the new value | useShared() |
A host that does not know an event ignores it. In a page with no storefront host (a plain test page),
no …:updated answer comes, so ready stays false.
Note. In bizzpocket dev the events fire, but there is no real cart or account behind them.
A click shows no cart change there. On a real storefront the host handles them.
Worked example: size picker, live price and add to cart
A product page buy box that uses each kind of state once:
- Server HTML: the title, the option buttons and the variant table. They are the same for every shopper.
- SIR:
sir.variantPickerhandles the size buttons, with no React. It writesvariant:<productId>. - Shared state: the island follows
variant:<productId>withuseShared. - Local state: the quantity, with
useState. - The cart:
useCartActions()adds the chosen size.useCart()shows how many are already in the cart.
The island, blocks/buy-panel/buy-panel-island.tsx:
'use client';
import { useState } from 'react';
import { useCart, useCartActions, useShared } from '@bizzpocket/theme/client';
type Money = { amount: number; currency: string };
type Row = { id: string; price: Money; inStock: boolean };
/** What SIR's variant picker writes under `variant:<productId>`. */
export type Choice = { productId: string; variantId: string | null; variant: Row | null };
export function BuyPanel({ productId, handle, locale, opening }: { productId: string; handle: string; locale: string; opening: Choice }) {
// Shared: the variant the shopper picked. Starts with the server's opening choice.
const [choice] = useShared<Choice>(`variant:${productId}`, opening);
// Local: only this island needs the quantity.
const [qty, setQty] = useState(1);
const [added, setAdded] = useState(false);
// The cart: actions for the button, and the lines already in the cart.
const { add, pending, error } = useCartActions();
const { cart, ready } = useCart();
const v = choice.variant;
const inCart = cart?.items.filter((l) => l.productId === productId).reduce((n, l) => n + l.quantity, 0) ?? 0;
const total = v === null ? null : new Intl.NumberFormat(locale, { style: 'currency', currency: v.price.currency }).format(v.price.amount * qty);
const onAdd = () => {
if (v === null) return;
setAdded(false);
add({ productId, variantId: v.id, handle, quantity: qty }).then(
() => setAdded(true),
() => {}, // `error` holds the reason
);
};
return (
<div>
<p aria-live="polite">{total ?? 'Choose a size'}</p>
<label>
Quantity{' '}
<input type="number" min={1} max={10} value={qty} onChange={(e) => setQty(Math.min(10, Math.max(1, Number(e.target.value) || 1)))} />
</label>
<button type="button" disabled={v === null || !v.inStock || pending} onClick={onAdd}>
{v === null ? 'Choose a size' : !v.inStock ? 'Sold out' : pending ? 'Adding...' : 'Add to cart'}
</button>
<p role="status">{added ? 'Added to your cart.' : ready && inCart > 0 ? `${inCart} already in your cart.` : ''}</p>
{error !== null && <p role="alert">{error.message}</p>}
</div>
);
}The block, blocks/buy-panel/buy-panel.tsx. It renders the size buttons with SIR and gives the island
the opening choice, so the server HTML and the first browser render match:
import { block, product, sir } from '@bizzpocket/theme';
import { BuyPanel, type Choice } from './buy-panel-island';
const LOCALE = 'en-IN';
export default block({
name: 'Buy panel',
category: 'commerce',
// The buy box is on the first screen: make it interactive at once.
hydrate: 'load',
data: (_props, page) => ({ item: product({ handle: page.route.handle }) }),
render: ({ item }) => {
if (!item) return null;
// The variant table, as plain data: one row per variant.
const rows = item.variants.map((v) => ({
id: v.id,
options: Object.fromEntries(v.options.map((o) => [o.name, o.value])),
price: v.price,
inStock: v.inStock,
}));
const { groups, variant } = sir.variantState(rows);
const opening: Choice = {
productId: item.id,
variantId: variant?.id ?? null,
variant: variant ? { id: variant.id, price: variant.price, inStock: variant.inStock } : null,
};
return (
<section>
<h1>{item.title}</h1>
<div {...sir.variantPicker({ 'data-product-id': item.id, 'data-locale': LOCALE })}>
{groups.map((g) => (
<fieldset key={g.name}>
<legend>{g.name}</legend>
<div {...sir.variantGroup(g.name)}>
{g.values.map((v) => (
<button key={v.value} type="button" {...sir.variantOption({ name: g.name, ...v })}>
{v.value}
</button>
))}
</div>
</fieldset>
))}
<script {...sir.variantData(rows)} />
</div>
<BuyPanel productId={item.id} handle={item.handle} locale={LOCALE} opening={opening} />
</section>
);
},
});What happens:
- The server renders the size buttons with the first in-stock size selected, and the island with the same opening choice. The page is complete before any JavaScript runs.
- SIR starts and sets
variant:<productId>to the opening choice. It is the same value, so nothing changes on screen. - The shopper picks a size. SIR updates the buttons and the shared value. The island renders the new price times the quantity, and enables or disables the button.
- The shopper clicks Add to cart. The island sends
bizzpocket:cart:add. The host adds the line, opens its cart drawer and sendsbizzpocket:cart:updated. The Promise resolves, anduseCart()now counts the new line.
Only one island ships JavaScript here. The size buttons cost nothing, because the SIR runtime is already on the page.
Patterns
- Start on the server. Render everything that is the same for every shopper in
render(), and pass it to islands as props. An island should add behaviour, not fetch the page's content. - Give
useSharedthe server's value asinitial. Then the first browser render matches the server HTML, and nothing flickers when the island wakes up. - One key, one owner. Let one island (or SIR) write a key and the others read it. Two writers that disagree make a value that jumps.
- Use
ready. Show a neutral state (Account, no count) until the host has answered. Do not treat "no answer yet" as "guest" or "empty cart". - Keep the box size fixed between the first render and the answer, so the page does not shift.
- Put list state in the URL. A filter, a sort or a page number is a link (
?sort=price). The page is rebuilt on the server, can be shared and bookmarked, and needs no JavaScript.
Anti-patterns
- Personal data in
data()orrender(). The server HTML is shared by every shopper. There is no cart or shopper on the server to read, andload()makes the page uncacheable. Use the hooks. - A module-level variable as a store.
let size = 'M'at the top of an island file gives each island its own copy, because islands are bundled separately. UseuseShared. localStoragefor page state. It outlives the page, is shared by every tab, and differs from the server HTML, so the first render mismatches. Keep it for real preferences, read it in an effect, and never store tokens or personal data in it.- Copying the cart into
useState. Your copy goes stale when another island or the cart drawer changes the cart. ReaduseCart()where you need it. - Secrets in props. Island props are written into the page as JSON, for anyone to read. Pass only what the shopper may see. See limits.md.
- Writing someone else's key.
variant:<productId>belongs to SIR's variant picker. Read it, do not set it.
Next: forms.md.