Cursor rule that enforces the Rules of Hooks and React purity with eslint-plugin-react-hooks 7, a zero-warning CI policy, correct error handling and renderHook tests.
.cursor/rules/react-hooks-strict-rules.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule that enforces the Rules of Hooks and React purity with eslint-plugin-react-hooks 7, a zero-warning CI policy, correct error handling and renderHook tests."
globs: "**/*"
alwaysApply: false
---
# React Hooks Strict Rules (enforced by lint and tests)
Applies to: every React component and custom hook in the repository. This rule defines what is non-negotiable and how it is enforced in CI. For design guidance (when to use effects, memoisation, reducers), follow the project's general hooks guidance.
Version baseline: checked against the React 19 "Rules of React" docs and `eslint-plugin-react-hooks` 7.x (which adds the React Compiler-based rules). Read the installed plugin version: in 7.0.x the flat config is exported as `configs.flat.recommended`; check the plugin README for the version you have.
## The two Rules of Hooks (lint: `react-hooks/rules-of-hooks`, error)
1. Call hooks only at the top level: not in conditions, loops, nested functions, `try`/`catch`/`finally` blocks, or after a conditional `return`.
2. Call hooks only from React function components or custom hooks, never from regular functions, class components or event handlers.
```tsx
// ❌ conditional hook
function Profile({ userId }: { userId?: string }) {
if (!userId) return null;
const [tab, setTab] = useState("posts"); // runs after an early return
}
// ✅ hooks first, then branch
function ProfileFixed({ userId }: { userId?: string }) {
const [tab, setTab] = useState("posts");
if (!userId) return null;
return <Tabs value={tab} onChange={setTab} />;
}
```
## Naming
- A function that calls hooks must be named `useSomething` (camelCase with the `use` prefix), so the linter can check it. Do not use the `use` prefix for functions that call no hooks.
## Purity and immutability (Rules of React)
- Components and hooks are pure during render: same inputs, same output, and no side effects (no network calls, subscriptions, `Math.random()`/`Date.now()` that changes output, or mutation of outside variables).
- Never mutate props, state, hook return values or values passed to JSX. Create new objects and arrays.
- Do not call `setState` unconditionally during render, and do not set state synchronously in an effect just to derive a value from props or state. Compute it during render instead. The recommended config includes `react-hooks/set-state-in-render` and `react-hooks/set-state-in-effect`, but they do not flag every case, so review for this pattern too.
- Do not read or write `ref.current` during render (lint: `react-hooks/refs`).
## Dependencies (lint: `react-hooks/exhaustive-deps`)
- Every reactive value read inside `useEffect`/`useLayoutEffect`/`useMemo`/`useCallback` is in the dependency array. Fix warnings by restructuring the code (move values inside the effect, use updater functions, use `useEffectEvent` for non-reactive logic), never by deleting dependencies.
## Errors
- Hooks cannot catch rendering errors, and React has no `useErrorBoundary` hook. Render errors are caught by a class error boundary or a framework boundary (Next.js `error.tsx`). `useErrorBoundary().showBoundary()` exists only in the third-party `react-error-boundary` package. Use it only if the project depends on it.
- Wrap async work inside effects and handlers in `try/catch` and store the error in state, or rethrow it during render via a state updater so the nearest boundary handles it.
- Effects that start async work must handle cancellation (`AbortController`, or an `ignore` flag in cleanup) so stale responses do not set state.
## Lint configuration (flat config, plugin 7.0.x)
```js
// eslint.config.js
import reactHooks from "eslint-plugin-react-hooks";
export default [
{
files: ["**/*.{js,jsx,ts,tsx}"],
...reactHooks.configs.flat.recommended,
},
];
```
- In CI, run `eslint . --max-warnings 0`, so `exhaustive-deps` warnings fail the build.
- `// eslint-disable-next-line react-hooks/...` is allowed only with a comment that explains why and links an issue. Whole-file disables are not allowed.
## Testing custom hooks
- Test custom hooks with `renderHook` from `@testing-library/react`. The separate `@testing-library/react-hooks` package supports only React 16.9/17 (its peer range), and its README points React 18+ users to `@testing-library/react`. Wrap updates in `act()`, and test hooks through a real component when their behaviour depends on the DOM.
```tsx
import { renderHook, act } from "@testing-library/react";
import { useCounter } from "./useCounter";
test("increments", () => {
const { result } = renderHook(() => useCounter(1));
act(() => result.current.increment());
expect(result.current.count).toBe(2);
});
```
## Verify before finishing
- `npx eslint <changed files> --max-warnings 0` passes with no new disable comments.
- `npx tsc --noEmit` passes, and the hook/component tests pass under `<StrictMode>`.
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
coding
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A team wants Cursor to treat hook-rule violations as build failures and to fix existing violations before merging.
Turn on strict hook linting in eslint.config.js (flat config, eslint-plugin-react-hooks 7.0.1) and fix violations in src/features/profile. One file uses useErrorBoundary from 'react', and the hook tests import renderHook from @testing-library/react-hooks. CI should fail on warnings.
Illustrative; not a recorded model run. An eslint.config.js entry spreading reactHooks.configs.flat.recommended, and a CI lint command with --max-warnings 0. Conditional hooks are moved above early returns, missing dependencies are fixed by restructuring, and refs are no longer read during render. The useErrorBoundary import is replaced: React has no such hook, so the fix is a class or framework boundary, or react-error-boundary if it is a project dependency. renderHook imports are switched to @testing-library/react with act(). No new eslint-disable lines are added.
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-hooks-strict-rules.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 Hooks Strict Rules: Rules of Hooks, Purity and Lint Enforcement project conventions"
globs: "**/*"
alwaysApply: false
---
# React Hooks Strict Rules (enforced by lint and tests)
Applies to: every React component and custom hook in the repository. This rule defines what is non-negotiable and how it is enforced in CI. For design guidance (when to use effects, memoisation, reducers), follow the project's general hooks guidance.
Version baseline: checked against the React 19 "Rules of React" docs and `eslint-plugin-react-hooks` 7.x (which adds the React Compiler-based rules). Read the installed plugin version: in 7.0.x the flat config is exported as `configs.flat.recommended`; check the plugin README for the version you have.
## The two Rules of Hooks (lint: `react-hooks/rules-of-hooks`, error)
1. Call hooks only at the top level: not in conditions, loops, nested functions, `try`/`catch`/`finally` blocks, or after a conditional `return`.
2. Call hooks only from React function components or custom hooks, never from regular functions, class components or event handlers.
```tsx
// ❌ conditional hook
function Profile({ userId }: { userId?: string }) {
if (!userId) return null;
const [tab, setTab] = useState("posts"); // runs after an early return
}
// ✅ hooks first, then branch
function ProfileFixed({ userId }: { userId?: string }) {
const [tab, setTab] = useState("posts");
if (!userId) return null;
return <Tabs value={tab} onChange={setTab} />;
}
```
## Naming
- A function that calls hooks must be named `useSomething` (camelCase with the `use` prefix), so the linter can check it. Do not use the `use` prefix for functions that call no hooks.
## Purity and immutability (Rules of React)
- Components and hooks are pure during render: same inputs, same output, and no side effects (no network calls, subscriptions, `Math.random()`/`Date.now()` that changes output, or mutation of outside variables).
- Never mutate props, state, hook return values or values passed to JSX. Create new objects and arrays.
- Do not call `setState` unconditionally during render, and do not set state synchronously in an effect just to derive a value from props or state. Compute it during render instead. The recommended config includes `react-hooks/set-state-in-render` and `react-hooks/set-state-in-effect`, but they do not flag every case, so review for this pattern too.
- Do not read or write `ref.current` during render (lint: `react-hooks/refs`).
## Dependencies (lint: `react-hooks/exhaustive-deps`)
- Every reactive value read inside `useEffect`/`useLayoutEffect`/`useMemo`/`useCallback` is in the dependency array. Fix warnings by restructuring the code (move values inside the effect, use updater functions, use `useEffectEvent` for non-reactive logic), never by deleting dependencies.
## Errors
- Hooks cannot catch rendering errors, and React has no `useErrorBoundary` hook. Render errors are caught by a class error boundary or a framework boundary (Next.js `error.tsx`). `useErrorBoundary().showBoundary()` exists only in the third-party `react-error-boundary` package. Use it only if the project depends on it.
- Wrap async work inside effects and handlers in `try/catch` and store the error in state, or rethrow it during render via a state updater so the nearest boundary handles it.
- Effects that start async work must handle cancellation (`AbortController`, or an `ignore` flag in cleanup) so stale responses do not set state.
## Lint configuration (flat config, plugin 7.0.x)
```js
// eslint.config.js
import reactHooks from "eslint-plugin-react-hooks";
export default [
{
files: ["**/*.{js,jsx,ts,tsx}"],
...reactHooks.configs.flat.recommended,
},
];
```
- In CI, run `eslint . --max-warnings 0`, so `exhaustive-deps` warnings fail the build.
- `// eslint-disable-next-line react-hooks/...` is allowed only with a comment that explains why and links an issue. Whole-file disables are not allowed.
## Testing custom hooks
- Test custom hooks with `renderHook` from `@testing-library/react`. The separate `@testing-library/react-hooks` package supports only React 16.9/17 (its peer range), and its README points React 18+ users to `@testing-library/react`. Wrap updates in `act()`, and test hooks through a real component when their behaviour depends on the DOM.
```tsx
import { renderHook, act } from "@testing-library/react";
import { useCounter } from "./useCounter";
test("increments", () => {
const { result } = renderHook(() => useCounter(1));
act(() => result.current.increment());
expect(result.current.count).toBe(2);
});
```
## Verify before finishing
- `npx eslint <changed files> --max-warnings 0` passes with no new disable comments.
- `npx tsc --noEmit` passes, and the hook/component tests pass under `<StrictMode>`.
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.