/storefront-next:sfnext-state-managementfrom storefront-next
Guides choosing the right state mechanism in a Storefront Next project: loader data, URL state, cookies, optimistic UI, React context providers, and useSyncExternalStore stores. Covers basket, auth, wishlist, mini-cart, and product context.
Ships in storefront-next. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Server state lives in loaders and actions. Client state is small and local. There is no global client store library in the template (Zustand was removed): use the tools below in this order. docs/README-STATE.md and docs/README-DATA.md in your project cover each in depth.
| State | Use |
|---|---|
| Data from SCAPI | loader + loaderData; action for writes |
| Another route's loader data | useRouteLoaderData('routes/_app') (route id = file path without extension) |
| Filters, sort, pagination, tab | URL: useSearchParams / useParams (shareable, SSR-friendly) |
| Must survive requests, read by server | cookies (createCookie from @/lib/cookie-utils.server) or session helpers |
| Pending or optimistic result | fetcher.formData, useNavigation, useOptimistic |
| Form fields, toggles, open/close in one component | useState / useReducer |
| Shared by a subtree | React context with a provider at the owning layout |
| Shared app-wide and read outside React, or high-frequency | module-level useSyncExternalStore store |
| Request-scoped server values (site, auth, basket) | router context (middleware), read with context.get(...) |
Prefer the earliest row that works. Never copy loader data into useState to "cache" it.
| Need | API |
|---|---|
| Basket | BasketProvider in src/providers/basket.tsx: useBasket({ autoLoad }), useBasketSnapshot, useBasketHydrated, useBasketError, useBasketUpdater, useBasketReset, useBasketLoader, useBasketReconcile; BasketCookieReconciler syncs the cookie |
| Session info | useAuth() from @/providers/auth |
| Product / variant selection | @/providers/product-context, @/providers/product-view |
| Image widths | DynamicImageProvider (@/providers/dynamic-image) |
| Wishlist | src/providers/wishlist.ts (module-level store) |
| Mini-cart open state | useMiniCartStore, setMiniCartOpen in src/hooks/mini-cart-store.ts |
| Cart toast | src/hooks/cart-mutation-toast-store.ts |
| Shopper context | useShopperContext (@/hooks/use-shopper-context) |
The basket is loaded through useScapiFetcher('shopperBasketsV2', 'getBasket') and is updated from action results via updateBasketResource (server side, @/middlewares/basket.server), so after a basket action components simply re-render from useBasket(). The __sfdc_basket cookie carries the basket id; __sfdc_usertype is the user-type hint. Do not read these directly in components; use the hooks. Server reads: getBasket, getBasketSnapshot, ensureBasketId, destroyBasket, and getAuth, updateAuth, destroyAuth from @/middlewares/auth.server.
const fetcher = useFetcher<typeof action>();
const removing = fetcher.formData?.get('itemId') === item.itemId;
return <li hidden={removing}>...</li>;
Use useOptimistic for values the server will confirm, and useNavigation for URL-driven pending states. Roll back by reading the confirmed loaderData/basket value; never hand-maintain a parallel copy.
Use when state is global, changes often, or must be set outside React. Follow src/hooks/mini-cart-store.ts:
import { useSyncExternalStore } from 'react';
interface State { open: boolean }
let state: State = { open: false };
const SERVER_STATE: State = Object.freeze({ open: false });
const listeners = new Set<() => void>();
const subscribe = (l: () => void) => { listeners.add(l); return () => void listeners.delete(l); };
export const setOpen = (open: boolean) => {
if (open === state.open) return; // skip no-op writes
state = { ...state, open };
listeners.forEach((l) => l());
};
export function useDrawerStore<T>(select: (s: State) => T): T {
return useSyncExternalStore(subscribe, () => select(state), () => select(SERVER_STATE));
}
Rules:
getSnapshot must return a referentially stable value when nothing changed. Select primitives; a selector that allocates per call loops forever.createStoreLocatorStore does in the store-locator extension.value (useMemo, useCallback) and split read-only state from updaters into separate contexts so updater-only consumers do not re-render.useRef, not context state.src/providers/compose-providers.tsx.More patterns and anti-patterns in PATTERNS.md.
| Mistake | Instead |
|---|---|
useEffect that fetches on mount and stores in state | loader (or streamed promise) |
Copying loaderData or basket into useState | read directly; derive with plain expressions |
Filters in useState | useSearchParams |
| Reading cookies in components | loader returns the value, or use the provider hook |
| New context for one component's state | useState in that component |
| Adding Zustand or Redux | the mechanisms above; check storefront-next:sfnext-overview for conventions |
AGENTS.md ("Key Documentation"), docs/README-STATE.md, docs/README-DATA.md. b2c docs search "storefront next state" or the docs_search MCP tool.
storefront-next:sfnext-data-fetching - loaders, actions, fetchersstorefront-next:sfnext-revalidation - when providers make a re-run unnecessarystorefront-next:sfnext-performance - hydration stability and render scopestorefront-next:sfnext-authentication - useAuth and session lifecyclestorefront-next:sfnext-commerce-features - cart, wishlist, checkout featuresstorefront-next:sfnext-components - component conventionsWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
storefront-next, state-management, react-state, optimistic-ui, basket, auth
npx claudepluginhub salesforcecommercecloud/b2c-developer-tooling --plugin storefront-next25 skills in this plugin
/sfnext-accessibilityBuild and fix accessible UI in a Storefront Next storefront (WCAG 2.1 AA): jsx-a11y lint findings, missing accessible names and labels, form error association, dialog focus management, aria-live status messages, keyboard behavior, color contrast, and verifying fixes with Storybook a11y/play() tests and the e2e axe scan with its baseline. Use for "accessibility", "a11y", "WCAG", "screen reader", "aria-label", "focus trap", "axe violation", pnpm lint:a11y, pnpm a11y, a11y-baseline.json, skip-a11y, STORYBOOK_A11Y_TEST_MODE, or an accessibility audit finding to fix. Do not use for general lint/typecheck gates (use `storefront-next:sfnext-quality-gates`), writing non-accessibility tests (use `storefront-next:sfnext-testing`), or color/token design (use `storefront-next:sfnext-theming`)./sfnext-analytics-consentStorefront Next analytics: engagement adapters (Einstein, Active Data, Data 360), adding a custom adapter, tracking consent gating, PageViewTracker, useAnalytics events, and first-touch attribution (dw_attribution). Use when configuring engagement.adapters in config.server.ts, writing an adapter with hasConsent, registering it in initializeEngagementAdapters, wiring the consent banner (trackingConsent, consentCategories, dw_dnt), firing trackViewProduct/trackCartItemAdd events, debugging why no analytics events are sent, or passing campaign attribution to orders. Do not use for general config loading or env vars (use `storefront-next:sfnext-configuration`), CSP/script allowlisting of third-party tags (use `storefront-next:sfnext-security`), or SEO meta/JSON-LD (use `storefront-next:sfnext-seo`)./sfnext-authenticationWork with Storefront Next's server-only authentication and session architecture (SLAS guest/registered tokens, httpOnly cookies, auth.server.ts middleware). Use for getAuth, useAuth, updateAuth, destroyAuth, protecting account routes, login/logout actions, guest-to-registered basket/wishlist merge, "session expired" redirects, 401 recovery loops, cc-at/cc-nx/usid/dwsid cookies, cookie names or expiry, passwordless login, social login, OTP email verification, passkeys, guest order lookup, or refresh-token lifetime settings. Do not use for Turnstile, CSP headers or cookie-domain config (use `storefront-next:sfnext-security`), calling SCAPI clients (use `storefront-next:sfnext-scapi`), or sharing sessions with SFRA (use `storefront-next:sfnext-hybrid-storefronts`)./sfnext-commerce-featuresCatalogue and router for optional Storefront Next commerce features: Shopper Context (qualifiers, source codes), Order Management returns/cancel/tracking (SOM/OMS), delivery estimates, feature stubs (@feature-stub), guest order lookup, the app_storefrontnext_base email cartridge, and the shipped extensions (bnpl, bopis, multiship, store-locator, ratings-reviews, customer-preferences, product-content, shipping-delivery, theme-switcher). For each: which flag, SLAS scope, Business Manager setting, cartridge, or extension registry entry it needs, and which in-project doc to read. Use when asked how to enable a feature, why a feature does not render, what prerequisites a feature has, or which stubs are mock data. Do not use for building a new extension (use `storefront-next:sfnext-extensions`), config loading (use `storefront-next:sfnext-configuration`), or SLAS login flows (use `storefront-next:sfnext-authentication`)./sfnext-componentsBuild and modify UI components in a Storefront Next storefront: page components with Suspense and use()/Await, createPage and withSuspense, Tailwind v4 token classes, shape tokens (rounded-ui, shadow-ui, border-ui), shadcn/ui primitives in src/components/ui (sync-shadcn), CVA variants, data-slot, DynamicImage, lazy-loaded overlays, and Storybook stories with snapshot tests. Use when creating or editing a component in src/components, adding a shadcn primitive, fixing styling that ignores the theme, writing a *.stories.tsx file, or running pnpm storybook:test. Do not use for re-branding colors, fonts, or logos (use `storefront-next:sfnext-theming`), route loaders (use `storefront-next:sfnext-data-fetching`), or Page Designer registration (use `storefront-next:sfnext-page-designer`)./sfnext-configurationConfigure a Storefront Next app: config.server.ts (defineConfig, metadata/runtime/app), AppConfig types in src/types/config.ts, PUBLIC__ environment variable overrides, getConfig(context) / useConfig(), extension config (app.extension, app.serverExtension), protected paths, server-only secrets, and multi-site settings (commerce.sites, url.prefix, seoRoutes, siteAliasMap, cookie domain). Use when editing config.server.ts, adding a config value, an env var is ignored or "not applied", `pnpm config:inspect` / `config:push-env`, "Ignoring environment variable" warnings, protected config path errors, setting up a second site or locale URLs, or going through the pre-launch config checklist. Do not use for creating a project or the npm script list (use `storefront-next:sfnext-project-setup`), pushing bundles or MRT env management (use `storefront-next:sfnext-deployment` / `b2c-cli:b2c-mrt`), or hybrid proxy and cookie-sharing with SFRA (use `storefront-next:sfnext-hybrid-storefronts`).Other plugins' skills for the same job