Decide where React state lives, keep server data out of component state, and model complex UI states so impossible combinations cannot occur.
.cursor/rules/react-state-management-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Decide where React state lives, keep server data out of component state, and model complex UI states so impossible combinations cannot occur."
globs: "**/*"
alwaysApply: false
---
Apply these guidelines when adding or refactoring state in React components.
## Where state lives
- Start with local `useState` in the component that uses the value. Lift it to the closest common parent only when sibling components must read or change the same value.
- Derive values during render instead of storing them (for example a filtered list computed from `items` and `query`). Do not copy props into state or keep two pieces of state in sync with `useEffect`.
- Before adding context, try composition: pass `children` or elements as props so intermediate components do not need the data. Use context for values many distant components read (theme, locale, current user), and split contexts so a frequently changing value does not re-render unrelated consumers.
- Keep state that should survive a reload or be shareable (filters, tabs, pagination) in the URL search params.
## Server data is a cache, not component state
- Fetch, cache, invalidate and refetch server data through the project's data layer (framework loaders or Server Components, TanStack Query, SWR, etc.). Keep only UI concerns in React state: open/closed, selection, unsaved drafts.
- Do not copy fetched data into a global client store unless you need offline editing or cross-page drafts.
## Model complex UI states explicitly
When several flags must never combine (loading and error at the same time, "success" without data), use a discriminated union with `useReducer`, or a state-machine library when there are many transitions:
```tsx
type FetchState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };
type FetchAction<T> =
| { type: 'start' }
| { type: 'resolve'; data: T }
| { type: 'reject'; message: string };
export function fetchReducer<T>(state: FetchState<T>, action: FetchAction<T>): FetchState<T> {
switch (action.type) {
case 'start':
return { status: 'loading' };
case 'resolve':
return { status: 'success', data: action.data };
case 'reject':
return { status: 'error', message: action.message };
}
}
```
- Every async view renders its loading, empty, error and success states.
## Optimistic updates
- Use optimistic UI only for actions that usually succeed and can be reverted, through React's `useOptimistic` or your data library's optimistic-update API. On failure, roll back and show the error.
## When proposing changes
- Say where each new piece of state lives and why, and point out duplicated or derivable state you removed.
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A users panel keeps users, filteredUsers, isLoading and error in four useState calls and syncs filteredUsers with a useEffect; the two flags can both be true after a failed retry.
Using the React State Management Patterns rule, refactor src/features/users/UsersPanel.tsx. Data comes from GET /api/users; the search box filters by name.
filteredUsers is computed during render from users and the query; the sync effect is removed; fetching goes through the project's data layer or a reducer over a status union (idle/loading/success/error) so loading and error cannot both be set; the search query is a URL param if the page is shareable; the answer explains where each piece of state lives.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/react-state-management-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "React State Management Patterns project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these guidelines when adding or refactoring state in React components.
## Where state lives
- Start with local `useState` in the component that uses the value. Lift it to the closest common parent only when sibling components must read or change the same value.
- Derive values during render instead of storing them (for example a filtered list computed from `items` and `query`). Do not copy props into state or keep two pieces of state in sync with `useEffect`.
- Before adding context, try composition: pass `children` or elements as props so intermediate components do not need the data. Use context for values many distant components read (theme, locale, current user), and split contexts so a frequently changing value does not re-render unrelated consumers.
- Keep state that should survive a reload or be shareable (filters, tabs, pagination) in the URL search params.
## Server data is a cache, not component state
- Fetch, cache, invalidate and refetch server data through the project's data layer (framework loaders or Server Components, TanStack Query, SWR, etc.). Keep only UI concerns in React state: open/closed, selection, unsaved drafts.
- Do not copy fetched data into a global client store unless you need offline editing or cross-page drafts.
## Model complex UI states explicitly
When several flags must never combine (loading and error at the same time, "success" without data), use a discriminated union with `useReducer`, or a state-machine library when there are many transitions:
```tsx
type FetchState<T> =
| { status: 'idle' }
| { status: 'loading' }
| { status: 'success'; data: T }
| { status: 'error'; message: string };
type FetchAction<T> =
| { type: 'start' }
| { type: 'resolve'; data: T }
| { type: 'reject'; message: string };
export function fetchReducer<T>(state: FetchState<T>, action: FetchAction<T>): FetchState<T> {
switch (action.type) {
case 'start':
return { status: 'loading' };
case 'resolve':
return { status: 'success', data: action.data };
case 'reject':
return { status: 'error', message: action.message };
}
}
```
- Every async view renders its loading, empty, error and success states.
## Optimistic updates
- Use optimistic UI only for actions that usually succeed and can be reverted, through React's `useOptimistic` or your data library's optimistic-update API. On failure, roll back and show the error.
## When proposing changes
- Say where each new piece of state lives and why, and point out duplicated or derivable state you removed.
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.