Cursor rule for React hooks covering when effects are needed, honest dependency arrays, useEffectEvent, cleanup, compiler-aware memoisation, refs and useReducer.
.cursor/rules/react-hooks-best-practices.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for React hooks covering when effects are needed, honest dependency arrays, useEffectEvent, cleanup, compiler-aware memoisation, refs and useReducer."
globs: "**/*"
alwaysApply: false
---
# React Hooks Best Practices
Applies to: React function components and custom hooks (`use*`) in `.tsx`/`.jsx`/`.ts` files.
Version baseline: checked against the React 19 docs, including `useEffectEvent` (React 19.2) and React Compiler 1.0. Read the `react` version in `package.json` and whether `babel-plugin-react-compiler` (or the framework's compiler option) is enabled. Several rules below depend on both.
## 1. Call hooks unconditionally at the top level
Call hooks only at the top level of components and custom hooks: never inside conditions, loops, nested functions, `try/catch`, or after an early `return`. Move the condition inside the hook, or split the component. (`use(promiseOrContext)` is the one API that may be called conditionally.)
## 2. Effects are for synchronising with external systems
- Before writing `useEffect`, check whether you need one. Compute derived values during render (`const fullName = first + " " + last`). Handle user actions in event handlers. Reset state with a `key` instead of an effect that watches props.
- Use effects for subscriptions, timers, DOM APIs, non-React widgets and network synchronisation. Prefer the framework's data fetching (Server Components, loaders) or a data library (TanStack Query, SWR) over hand-written fetch effects.
## 3. Dependencies: list every reactive value, never lie
- Include every prop, state value and function from the component body that the effect, `useMemo` or `useCallback` reads. The `react-hooks/exhaustive-deps` lint rule is the source of truth. Do not silence it.
- If the effect re-runs too often, change the code, not the array. Move objects and functions inside the effect, depend on primitive fields (`options.roomId`), use a state updater (`setCount(c => c + 1)`), or move non-reactive logic into `useEffectEvent` (React 19.2+).
```tsx
import { useEffect, useEffectEvent } from "react";
export function ChatRoom({ roomId, theme }: { roomId: string; theme: "light" | "dark" }) {
const onConnected = useEffectEvent(() => {
showToast(`Connected to ${roomId}`, theme); // reads the latest theme without re-connecting
});
useEffect(() => {
const connection = createConnection(roomId); // project API
connection.on("connected", onConnected);
connection.connect();
return () => connection.disconnect(); // cleanup on unmount and before re-running
}, [roomId]); // effect events are not dependencies
return null;
}
```
Call effect events only from inside effects. Do not pass them to other components or call them during render.
## 4. Always clean up
Return a cleanup function for every subscription, listener, timer, connection or in-flight request (`AbortController`). In development, StrictMode mounts, unmounts and re-mounts components to reveal missing cleanup. Do not work around that with refs that skip the second run.
## 5. Memoisation: measure first, and let the compiler do it when enabled
- With React Compiler enabled, do not add new `useMemo`/`useCallback`/`memo` for performance. The compiler memoises automatically. Keep existing ones unless removing them is verified safe.
- Without the compiler, use `useCallback` only when the function goes to a `memo` child or is a dependency of another hook, and `useMemo` only for computations that profiling shows are slow (or when referential identity matters). Memoising everything adds cost and noise.
## 6. Refs hold values that do not affect rendering
Use `useRef` for DOM nodes, timer ids and the latest value for imperative code. Do not read or write `ref.current` during render, except for lazy one-time initialisation. If a value appears in the UI, it belongs in state.
## 7. useReducer for related state transitions
When several state values change together, or the next state depends on an action type, use `useReducer` with a pure reducer. Keep side effects out of reducers.
```tsx
type State = { status: "idle" | "loading" | "error"; items: string[]; error?: string };
type Action = { type: "start" } | { type: "success"; items: string[] } | { type: "failure"; error: string };
export function reducer(state: State, action: Action): State {
switch (action.type) {
case "start": return { ...state, status: "loading", error: undefined };
case "success": return { status: "idle", items: action.items };
case "failure": return { ...state, status: "error", error: action.error };
}
}
```
## 8. Custom hooks share logic, not state
Extract repeated stateful logic into `useSomething` functions. Each call gets its own state. Name them for their purpose (`useOnlineStatus`), not their lifecycle (`useMount`), and keep their inputs and outputs typed.
## Verify before finishing
- Run ESLint with `eslint-plugin-react-hooks` (`recommended` config) and fix every `rules-of-hooks` error and `exhaustive-deps` warning without disable comments.
- Exercise the component in development StrictMode, and confirm subscriptions are not duplicated and cleanup runs.
- Type-check (`npx tsc --noEmit`) and run the component tests.
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 developer asks Cursor to fix a component whose effect re-subscribes on every render, or to write a new component that subscribes to an external source.
ChatRoom.tsx reconnects to the chat server every time the user toggles the theme, because the effect depends on [roomId, theme] (theme is only used for the 'connected' toast). There is also a useMemo around first + ' ' + last and an eslint-disable for exhaustive-deps. React 19.2, compiler enabled.
Illustrative; not a recorded model run. The toast logic moves into a useEffectEvent, so the effect depends only on [roomId]. The effect returns connection.disconnect() as cleanup. The useMemo for string concatenation is removed (derived during render; the compiler memoises if needed), and the eslint-disable comment is deleted with the warnings fixed by restructuring. The answer recommends checking in StrictMode that only one connection is open.
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-best-practices.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 Best Practices: Effects, Dependencies, Cleanup, Memoisation and useEffectEvent project conventions"
globs: "**/*"
alwaysApply: false
---
# React Hooks Best Practices
Applies to: React function components and custom hooks (`use*`) in `.tsx`/`.jsx`/`.ts` files.
Version baseline: checked against the React 19 docs, including `useEffectEvent` (React 19.2) and React Compiler 1.0. Read the `react` version in `package.json` and whether `babel-plugin-react-compiler` (or the framework's compiler option) is enabled. Several rules below depend on both.
## 1. Call hooks unconditionally at the top level
Call hooks only at the top level of components and custom hooks: never inside conditions, loops, nested functions, `try/catch`, or after an early `return`. Move the condition inside the hook, or split the component. (`use(promiseOrContext)` is the one API that may be called conditionally.)
## 2. Effects are for synchronising with external systems
- Before writing `useEffect`, check whether you need one. Compute derived values during render (`const fullName = first + " " + last`). Handle user actions in event handlers. Reset state with a `key` instead of an effect that watches props.
- Use effects for subscriptions, timers, DOM APIs, non-React widgets and network synchronisation. Prefer the framework's data fetching (Server Components, loaders) or a data library (TanStack Query, SWR) over hand-written fetch effects.
## 3. Dependencies: list every reactive value, never lie
- Include every prop, state value and function from the component body that the effect, `useMemo` or `useCallback` reads. The `react-hooks/exhaustive-deps` lint rule is the source of truth. Do not silence it.
- If the effect re-runs too often, change the code, not the array. Move objects and functions inside the effect, depend on primitive fields (`options.roomId`), use a state updater (`setCount(c => c + 1)`), or move non-reactive logic into `useEffectEvent` (React 19.2+).
```tsx
import { useEffect, useEffectEvent } from "react";
export function ChatRoom({ roomId, theme }: { roomId: string; theme: "light" | "dark" }) {
const onConnected = useEffectEvent(() => {
showToast(`Connected to ${roomId}`, theme); // reads the latest theme without re-connecting
});
useEffect(() => {
const connection = createConnection(roomId); // project API
connection.on("connected", onConnected);
connection.connect();
return () => connection.disconnect(); // cleanup on unmount and before re-running
}, [roomId]); // effect events are not dependencies
return null;
}
```
Call effect events only from inside effects. Do not pass them to other components or call them during render.
## 4. Always clean up
Return a cleanup function for every subscription, listener, timer, connection or in-flight request (`AbortController`). In development, StrictMode mounts, unmounts and re-mounts components to reveal missing cleanup. Do not work around that with refs that skip the second run.
## 5. Memoisation: measure first, and let the compiler do it when enabled
- With React Compiler enabled, do not add new `useMemo`/`useCallback`/`memo` for performance. The compiler memoises automatically. Keep existing ones unless removing them is verified safe.
- Without the compiler, use `useCallback` only when the function goes to a `memo` child or is a dependency of another hook, and `useMemo` only for computations that profiling shows are slow (or when referential identity matters). Memoising everything adds cost and noise.
## 6. Refs hold values that do not affect rendering
Use `useRef` for DOM nodes, timer ids and the latest value for imperative code. Do not read or write `ref.current` during render, except for lazy one-time initialisation. If a value appears in the UI, it belongs in state.
## 7. useReducer for related state transitions
When several state values change together, or the next state depends on an action type, use `useReducer` with a pure reducer. Keep side effects out of reducers.
```tsx
type State = { status: "idle" | "loading" | "error"; items: string[]; error?: string };
type Action = { type: "start" } | { type: "success"; items: string[] } | { type: "failure"; error: string };
export function reducer(state: State, action: Action): State {
switch (action.type) {
case "start": return { ...state, status: "loading", error: undefined };
case "success": return { status: "idle", items: action.items };
case "failure": return { ...state, status: "error", error: action.error };
}
}
```
## 8. Custom hooks share logic, not state
Extract repeated stateful logic into `useSomething` functions. Each call gets its own state. Name them for their purpose (`useOnlineStatus`), not their lifecycle (`useMount`), and keep their inputs and outputs typed.
## Verify before finishing
- Run ESLint with `eslint-plugin-react-hooks` (`recommended` config) and fix every `rules-of-hooks` error and `exhaustive-deps` warning without disable comments.
- Exercise the component in development StrictMode, and confirm subscriptions are not duplicated and cleanup runs.
- Type-check (`npx tsc --noEmit`) and run the component tests.
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.