Manage frontend state deliberately
"It shows the old value" and "these two parts disagree" are ownership bugs: a fact was
copied, and the copies drifted. For each fact decide one owner and one way it changes.
Server data belongs to the server-cache layer, UI state stays as local as possible,
shareable state lives in the URL, and a global store holds only client-owned global
facts.
Steps
Inventory the state the ticket touches and classify each fact:
| Kind |
Examples |
Owner |
| Server data |
lists, records, the current user's profile |
query/cache layer |
| URL state |
filters, sort, page, selected id, open tab |
router search params / path |
| Local UI state |
open/closed, hover, an input's draft |
the component, or nearest common parent |
| Global client state |
theme, auth session handle, cross-page draft |
the repo's store |
| Derived |
counts, filtered lists, "is valid" |
computed in render, never stored |
Call search_lore for the chosen libraries and conventions.
Server data stays in the cache layer (TanStack Query, SWR, RTK Query, Apollo,
loaders — the frontend-data-fetching skill). Read it where needed with the same
query key; do not copy it into useState or a store. To edit a record, keep only the
draft fields in form state, initialised from the query once, and submit a mutation.
Local first; lift only as far as needed. Two siblings that must agree share the
nearest common parent. Passing props through two or three levels is fine; deeper
usually wants composition (pass the rendered child) before context. Context carries
rarely changing values; split fast-changing values into their own context so a
keystroke does not re-render the tree.
URL for anything a user would share, bookmark or expect back. Parse search params
on read with a schema (unknown or invalid values fall back to defaults, never crash);
write with the router's API, replace for typing-driven changes and push for
navigations the Back button should undo. The URL is then the only copy — do not mirror
it into state.
A global store only for truly global client state, using the repo's library
(Zustand, Redux Toolkit, Pinia, signals). Small slices, actions named for intent
(selectTicket), selectors that return the minimum so subscribers re-render only when
their slice changes. External stores in React are read through the library's hooks or
useSyncExternalStore, never by subscribing in an effect.
Transitions are explicit and safe under concurrency.
- One named function per transition; reducers are pure (no fetches, no
Date.now(),
no mutation of the previous state).
- Updates that depend on the previous value use the functional form
(
setCount(c => c + 1)) so rapid events are not lost.
- Optimistic updates snapshot and roll back on failure, and a slower earlier response
must not overwrite a newer optimistic value (cancel or ignore superseded requests).
Persisted state (localStorage, IndexedDB) is versioned. Store a schema version,
migrate or discard old shapes on read, never persist server data or secrets, and read
it after hydration (or with the library's hydration helper) to avoid server/client
mismatches. If two tabs can edit the same persisted state, sync through the storage
event or BroadcastChannel, or declare last-write-wins in the ticket — do not leave it
undefined.
Reset deliberately. To reset a subtree's state when an entity changes, key it by
the entity id (<Editor key={ticketId} />) instead of an effect that clears fields.
Test where the state lives (the frontend-testing skill): pure reducer/store
transition tests; a component test per AC that drives the UI and asserts what is
shown; a URL test (load with params → correct view; change filter → URL updated; Back
restores); the rollback path; and rapid repeated events (click ×5 → count is 5). Record
per-AC evidence with the record-evidence skill, then stop.
Done when
Every fact the ticket touches has one named owner; no server data is duplicated in
local or global state; shareable state survives refresh and Back; each AC has a test
that exercises its behaviour through the UI.
Anti-patterns
useEffect(() => setX(props.y), [props.y]) — state mirroring props or query data.
- Storing derived values (
filteredItems, total) alongside their inputs.
- One app-wide context holding everything; a store slice per component.
- A second store library or query client next to the existing one.
- Persisted state with no version, restored before hydration.
Capture lore
This skill is one of the places durable, reusable knowledge naturally surfaces:
While classifying state you learn which library owns which kind of state here and how URL state is encoded. That kind of fact is lore. Capture it via the lore-capture
protocol in your brief (CLAUDE.factory.md, step 11 "Memory contribution"):
call the Memory MCP suggest_lore once at the close of your work — reusable
conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.
1---2name: frontend-state-management3description: Use when a ticket adds or reshapes client-side state — where data lives, how it flows between components, server cache versus UI state, a store, context, URL state, persisted drafts, optimistic updates, multiple tabs — and the result must keep one source of truth per fact and avoid the prop-drilling or global-store sprawl that makes UIs unpredictable. Invoke for "the state is out of sync", "lift this state", "add a store for X", or "the page resets when I navigate back".4stack: [react, web, next, vue, svelte, angular]5area: frontend6metadata:7 source: https://skillmd.com/skills/tmj-90/frontend-state-management8---910# Manage frontend state deliberately1112"It shows the old value" and "these two parts disagree" are ownership bugs: a fact was13copied, and the copies drifted. For each fact decide one owner and one way it changes.14Server data belongs to the server-cache layer, UI state stays as local as possible,15shareable state lives in the URL, and a global store holds only client-owned global16facts.1718## Steps19201. **Inventory the state the ticket touches** and classify each fact:2122 | Kind | Examples | Owner |23 |------|----------|-------|24 | Server data | lists, records, the current user's profile | query/cache layer |25 | URL state | filters, sort, page, selected id, open tab | router search params / path |26 | Local UI state | open/closed, hover, an input's draft | the component, or nearest common parent |27 | Global client state | theme, auth session handle, cross-page draft | the repo's store |28 | Derived | counts, filtered lists, "is valid" | computed in render, never stored |2930 Call `search_lore` for the chosen libraries and conventions.312. **Server data stays in the cache layer** (TanStack Query, SWR, RTK Query, Apollo,32 loaders — the `frontend-data-fetching` skill). Read it where needed with the same33 query key; do not copy it into `useState` or a store. To edit a record, keep only the34 draft fields in form state, initialised from the query once, and submit a mutation.353. **Local first; lift only as far as needed.** Two siblings that must agree share the36 nearest common parent. Passing props through two or three levels is fine; deeper37 usually wants composition (pass the rendered child) before context. Context carries38 rarely changing values; split fast-changing values into their own context so a39 keystroke does not re-render the tree.404. **URL for anything a user would share, bookmark or expect back.** Parse search params41 on read with a schema (unknown or invalid values fall back to defaults, never crash);42 write with the router's API, `replace` for typing-driven changes and `push` for43 navigations the Back button should undo. The URL is then the only copy — do not mirror44 it into state.455. **A global store only for truly global client state**, using the repo's library46 (Zustand, Redux Toolkit, Pinia, signals). Small slices, actions named for intent47 (`selectTicket`), selectors that return the minimum so subscribers re-render only when48 their slice changes. External stores in React are read through the library's hooks or49 `useSyncExternalStore`, never by subscribing in an effect.506. **Transitions are explicit and safe under concurrency.**51 - One named function per transition; reducers are pure (no fetches, no `Date.now()`,52 no mutation of the previous state).53 - Updates that depend on the previous value use the functional form54 (`setCount(c => c + 1)`) so rapid events are not lost.55 - Optimistic updates snapshot and roll back on failure, and a slower earlier response56 must not overwrite a newer optimistic value (cancel or ignore superseded requests).577. **Persisted state (localStorage, IndexedDB) is versioned.** Store a schema version,58 migrate or discard old shapes on read, never persist server data or secrets, and read59 it after hydration (or with the library's hydration helper) to avoid server/client60 mismatches. If two tabs can edit the same persisted state, sync through the `storage`61 event or `BroadcastChannel`, or declare last-write-wins in the ticket — do not leave it62 undefined.638. **Reset deliberately.** To reset a subtree's state when an entity changes, key it by64 the entity id (`<Editor key={ticketId} />`) instead of an effect that clears fields.659. **Test where the state lives** (the `frontend-testing` skill): pure reducer/store66 transition tests; a component test per AC that drives the UI and asserts what is67 shown; a URL test (load with params → correct view; change filter → URL updated; Back68 restores); the rollback path; and rapid repeated events (click ×5 → count is 5). Record69 per-AC evidence with the `record-evidence` skill, then stop.7071## Done when7273Every fact the ticket touches has one named owner; no server data is duplicated in74local or global state; shareable state survives refresh and Back; each AC has a test75that exercises its behaviour through the UI.7677## Anti-patterns7879- `useEffect(() => setX(props.y), [props.y])` — state mirroring props or query data.80- Storing derived values (`filteredItems`, `total`) alongside their inputs.81- One app-wide context holding everything; a store slice per component.82- A second store library or query client next to the existing one.83- Persisted state with no version, restored before hydration.8485## Capture lore8687This skill is one of the places durable, reusable knowledge naturally surfaces:88**While classifying state you learn which library owns which kind of state here and how URL state is encoded.** That kind of fact is *lore*. Capture it via the **lore-capture89protocol in your brief** (`CLAUDE.factory.md`, step 11 "Memory contribution"):90call the Memory MCP `suggest_lore` once at the close of your work — reusable91conventions, gotchas, decisions, and boundaries only, never per-ticket trivia.