zustand
Provides architectural patterns and best practices for implementing Zustand stores in React applications.
Install
mkdir -p .claude/skills/zustand && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/626" && unzip -o skill.zip -d .claude/skills/zustand && rm skill.zipInstalls to .claude/skills/zustand
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
LobeHub Zustand store conventions. Use when editing src/store, store slices, public/internal actions, dispatch actions, flattenActions, optimistic updates, selectors, maps, or class action migration.Key capabilities
- →Differentiate between public and internal action logic
- →Implement optimistic update patterns for UI responsiveness
- →Organize state into maps and ID arrays for lookup efficiency
- →Decouple state dispatchers from business logic functions
How it works
Applies a structured hierarchy of public actions, internal logic functions, and dispatchers to maintain separation of concerns within a store.
Inputs & outputs
When to use zustand
- →Implement complex state slices
- →Apply optimistic update patterns
- →Migrate class-based actions to store functions
- →Define internal versus public dispatch methods
About this skill
LobeHub Zustand State Management
State Shapes and Types
- Import shared store types from
@lobechat/types, not@lobechat/database. - Keep lightweight list-item types separate from full detail types; list types must not extend heavy detail types.
- Key cached details by id (
xxxDetailMap: Record<string, Detail>); never hold a singlecurrentDetailobject. - Read through
xxxSelectorsaggregates (selectors.ts), not ad-hoc lambdas repeated across components. - Before choosing list/detail shapes or type sources, read Data structures.
State-Only Stores (default for new and migrated stores)
Actions stay out of the Zustand state. Reference: src/store/page.
| File | Owns |
|---|---|
store.ts | useXStore = createWithEqualityFn<XState>()(devtools(() => initialState), shallow): state only, no methods |
privateAction.ts | XPrivateAction: replica slices, entity links, and write helpers shared by public actions. Not exported from index.ts |
action.ts | XActionImpl (the public API) and the singleton xActions = new XActionImpl(setState, getState, new XPrivateAction(…)) |
- Components read state with
useXStore(selector)and callxActions.foo()directly. Never select an action out of the store. - Sync hooks live on the public class and are called as
xActions.useFetchX(params). - Public actions call each other through
this.foo(). Private helpers are reached throughthis.#private. Do not addinternal_*methods to the store to share logic between classes. - Label every write:
this.#set(partial, false, n('actionName'))withconst n = setNamespace('x'). - Put
reset()on the public class and registerxActionsinresetableActionsinsrc/store/utils/userDataStores.ts. - Tests drive
xActionsand assert onuseXStore.getState(). To mock in component tests:vi.mock('@/store/x', () => ({ xActions: { foo: vi.fn() }, useXStore: … })).
Replica-Backed Server Data
Server lists and details the UI paints go through @/libs/replica, not a hand-written SWR onSuccess + reducer. The engine owns hydration from IndexedDB, head revalidation, paging, optimistic overlays with rollback, and scope (user + workspace) isolation. API reference: packages/replica/README.md.
- Define the resource (
defineReplica/definePagedReplica) in the store'sprojection.ts, converting server rows at the boundary. - Add two state fields per replica: the view (
xxxMap: Record<key, TData>) and its bookkeeping (xxxReplica: createReplicaState()). - Bind it in the private class:
createReplicaSlice(resource, { get, set, stateKey: 'xxxReplica', view: recordLens('xxxMap'), … }). When the same entity lives in several replicas (list row + detail), link them withlinkReplicaEntity([list, detail]). - Read:
slice.useSync(params)returns only fetch flags (isHydrated,isValidating,error,revalidate). Data comes from selectors overxxxMap. "Entry isundefined" is the loading signal — do not addxxxInitflags orloadingXxxIds. - Read with no view mounted (hover prefetch, refresh after a mutation):
await slice.fetch(params)({ fresh: true }after a write). Never call the service andslice.replace(...)by hand, because that skips the scope, removal, clear and superseded-request guards. Side effects of every response (not-found maps, seeding another store) go in the sliceeffects(onApplied/onMissing/onPurge/onError) withisMissing, not in one hook'sonSuccess. - Cold start without a skeleton:
useSynchydrates only after the component mounts. For a list that must paint from the local copy, add apreHydrateaction (ensureScope+hydrate) and call it from the route'sloaderthrough a lazy wrapper (src/spa/router/pageListLoader.ts,agentChatTopicListLoader.ts) bounded byPRE_PAINT_HYDRATE_TIMEOUT. - Write:
slice.optimistic(key, apply, serverCall)orentity.optimistic(id, fn | 'remove', serverCall). A failed call rolls back to the confirmed value, so deletes are optimistic too. Rows that exist only on the client (temp ids) are declared withisClientOnlyand seeded withupdate(key, fn, { persist: false }).
Outside test seeding, write a replica's view only through its slice. A plain set bypasses the engine's bookkeeping (persistence, rollback base, entity links).
Legacy Stores
Stores that still flatten action classes into state (flattenActions, create*Slice, internal_*, internal_dispatch* + reducers, SWR onSuccess syncing) follow Legacy slices. Use that layout only when editing one of those stores; migrate to the layouts above when moving its data onto a replica.
When not to use it
- →Managing simple local component state (use React.useState)
- →High-frequency numerical computation outside of state updates
Prerequisites
Limitations
- →Strict naming conventions for internal vs public methods
- →Requires manual state normalization for complex objects
How it compares
It follows specific LobeHub conventions for naming and action structure rather than generic state management patterns.
Compared to similar skills
zustand side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| zustand (this skill) | 113 | 4mo | No flags | Intermediate |
| react | 34 | 4mo | No flags | Intermediate |
| react-component-patterns | 3 | 3mo | No flags | Intermediate |
| zustand-5 | 8 | 9mo | No flags | Beginner |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by lobehub
View all by lobehub →You might also like
react
lobehub
React component development guide. Use when working with React components (.tsx files), creating UI, using @lobehub/ui components, implementing routing, or building frontend features. Triggers on React component creation, modification, layout implementation, or navigation tasks.
react-component-patterns
HoangNguyen0403
Modern React component architecture and composition patterns.
zustand-5
prowler-cloud
Zustand 5 state management patterns. Trigger: When implementing client-side state with Zustand (stores, selectors, persist middleware, slices).
1k-state-management
OneKeyHQ
Jotai state management patterns — atoms, globalAtom, contextAtom, and persistence.
react-router-getting-started
ssrjkk
Getting Started for React-Router: initial setup and first steps
accessibility-compliance
wshobson
Implement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.