Rule
0 installs · 0 said it worked
Zustand state management rules for React and TypeScript projects
Cursor rules that make the assistant follow React and TypeScript Zustand conventions: store design, selectors, middleware, persistence safety, SSR, and testing.
People use this for
- zustand react typescript rules
- zustand store cursor rules
- how to structure zustand stores
- zustand selectors and persistence guidelines
- write zustand store with typescript for react app
- Name
zustand-state-management-rules-for-react-and-typescript-projects- Works with
- Cursor
- License
- CC0(as observed at the source)
- Version
- v1 · updated Nov 29, 2026
Imported on Nov 29, 2026 from github.com . License observed at the source on Nov 29, 2026: CC0.
Are you the author?Claim this profileRequest removal
Use this rule
$ curl -fsSL "https://promptcommunity.dev/api/v1/posts/zustand-state-management-rules-for-react-and-typescript-projects-j5wp/export/mdc" -o .cursor/rules/zustand-state-management-rules-for-react-and-typescript-projects.mdcThen open a new session; Cursor picks it up from .cursor/rules/.
Manual install
Save zustand-state-management-rules-for-react-and-typescript-projects.mdc as .cursor/rules/zustand-state-management-rules-for-react-and-typescript-projects.mdc for this project or ~/.cursor/rules/zustand-state-management-rules-for-react-and-typescript-projects.mdc for every project, then start a new session.
Rule
description: "React and TypeScript state management guidance for Zustand stores, selectors, middleware, persistence, and testing." globs: **/*.ts, **/*.tsx alwaysApply: false
You are an expert in React, TypeScript, and Zustand state management.
React + Zustand Guidelines
State Ownership
- Keep ephemeral UI state in the nearest component with
useStateoruseReducer. - Use URL state for shareable filters, pagination, tabs, and search params.
- Use Zustand only for client state that is genuinely shared across unrelated components.
- Use TanStack Query, SWR, RTK Query, or the existing project data layer for server state.
- Never duplicate fetched server data into a Zustand store unless there is a documented offline or draft-editing requirement.
Store Design
- Model each store as state plus named actions; avoid exposing anonymous setters for component code to misuse.
- Keep stores small and domain-focused: auth session view state, command palette state, cart draft state, editor state, etc.
- Split large stores into typed slices, then apply middleware only at the composed store boundary.
- Keep derived values as selectors or small pure helpers unless they must be cached in state.
- Store serializable data by default; keep DOM nodes, promises, sockets, and timers outside store state.
import { create } from 'zustand'
interface SidebarState {
isOpen: boolean
activePanelId: string | null
}
interface SidebarActions {
openPanel: (panelId: string) => void
close: () => void
toggle: () => void
}
type SidebarStore = SidebarState & SidebarActions
export const useSidebarStore = create<SidebarStore>()((set) => ({
isOpen: false,
activePanelId: null,
openPanel: (panelId) => set({ isOpen: true, activePanelId: panelId }),
close: () => set({ isOpen: false, activePanelId: null }),
toggle: () => set((state) => ({ isOpen: !state.isOpen })),
}))
Component Usage
- Subscribe to the smallest possible slice:
useStore((state) => state.value). - Do not call a store hook without a selector in components unless the component truly needs every field.
- Select actions separately or through a shallow selector when grouping them.
- Use
useShallowfor object or tuple selectors that return multiple values. - Keep selectors pure and cheap; move expensive derivations into memoized helpers if needed.
import { useShallow } from 'zustand/react/shallow'
import { useSidebarStore } from '@/stores/sidebar-store'
export function SidebarToggle() {
const { isOpen, toggle } = useSidebarStore(
useShallow((state) => ({
isOpen: state.isOpen,
toggle: state.toggle,
})),
)
return (
<button type="button" aria-expanded={isOpen} onClick={toggle}>
Toggle sidebar
</button>
)
}
TypeScript
- Define explicit state and action interfaces for shared stores.
- Avoid
any; useunknownplus narrowing for external data. - Type action payloads and return values, including async actions.
- Prefer discriminated unions for complex local status instead of several loosely related booleans.
- Export store state types when tests, utilities, or vanilla store factories need them.
Updates and Middleware
- Use functional
set((state) => nextState)when the next value depends on current state. - Treat nested state immutably; install and use
immermiddleware only when it materially simplifies nested updates. - Use
persistonly for state that must survive reloads. - Use
partialize,version, andmigratewhen persisting anything beyond trivial preferences. - Never persist secrets, access tokens, refresh tokens, raw PII, or long-lived authorization state to browser storage.
- Use
devtoolsin development for complex flows and give important actions clear names. - Use
subscribeWithSelectorfor non-React subscriptions that need fine-grained updates.
Async Actions
- Async store actions may coordinate client-only workflows, optimistic drafts, or local device APIs.
- Keep HTTP fetching in the project's server-state layer unless the state is explicitly client-owned.
- Represent async client workflows with explicit statuses such as
idle,pending,success, anderror. - Reset error state deliberately when retrying or closing a workflow.
SSR and React Server Components
- Do not read or mutate browser-only stores from React Server Components.
- In SSR frameworks, create per-request vanilla stores when state must be initialized on the server.
- Guard persisted stores against hydration mismatches before rendering storage-backed values.
- Keep store modules free of direct
window,document, and storage access outside middleware configuration.
Testing
- Test store actions directly without rendering React when possible.
- Reset stores between tests with their initial state.
- Assert selectors and actions separately from component behavior.
- Mock server-state libraries instead of routing fetched data through Zustand for tests.
Anti-Patterns
- Do not create one global store for the entire application.
- Do not put form input state in Zustand unless multiple distant components edit the same draft.
- Do not mutate nested objects directly without Immer middleware.
- Do not use Zustand as an event bus; prefer explicit callbacks, services, or a scoped store.
- Do not introduce Redux-style reducers, action constants, or dispatch wrappers unless the project already uses that pattern.
No result recorded yet. Added it? File a Tried-it report so the next person knows how it went in your editor.
Tried it
Reports from people who added this rule to their editor. They roll up into the badges above.
No one has filed a report yet. Try the prompt and be the first.
Related rules
- Quality engineering agent role for risk-based test strategy and CI quality gates
A senior quality engineering role prompt that guides an assistant through risk-based test strategy, test automation architecture, CI/CD quality gates, edge-case analysis, and defect management, writing results to a TODO checklist file.
Coding · @wkaandemir
- Vue 3 and Pinia state management rules for coding assistants
Cursor rules that guide an assistant to write Vue 3 and TypeScript code using Pinia setup stores, correct state ownership, SSR-safe patterns, safe persistence, and store testing.
Coding · @patrickjs
- Cursor rules for writing and testing Xian smart contracts in Python
A Cursor rules file that guides the assistant through writing Xian blockchain smart contracts in Python, covering naming, state, context variables, events, error handling, and unittest-based testing with security checks.
Coding · @patrickjs
- Agent that writes, runs, and repairs tests after code changes
A system prompt defining a test-writer-fixer agent that writes unit, integration, and end-to-end tests, runs suites, analyzes failures, and repairs tests without weakening them.
Coding · @ersinyilmaz
- Universal agent rules for building React and Next.js projects
A reusable instruction set for AI coding agents covering stack choice, architecture, TypeScript, shadcn/ui, Tailwind, accessibility, and verification steps for React and Next.js projects.
Coding · @ramazanyusupov
License: CC0v1 · published Nov 29, 2026
Comments
No comments yet. If you tried this prompt, say how it went.