Cursor rule for profiling-driven React performance work with React Compiler, surgical memo, transitions, virtualisation, lazy loading and Web Workers.
.cursor/rules/react-performance-optimization.mdc. Downloaded files need to be placed in that repository path.---
description: "Cursor rule for profiling-driven React performance work with React Compiler, surgical memo, transitions, virtualisation, lazy loading and Web Workers."
globs: "**/*"
alwaysApply: false
---
# React Performance Optimization
Applies to: React client UI where rendering, interaction latency (INP) or bundle size is a measured problem.
Version baseline: checked against the React 19 docs (including React Compiler 1.0 and React 19.2 Performance Tracks). Read the `react` version, whether React Compiler is enabled, and the framework (Next.js, Vite, Remix) before choosing a technique.
## 0. Measure before and after
- Reproduce the slowness in a production build. Development builds are much slower and run StrictMode double renders.
- Record it with the React DevTools Profiler (which components rendered, why, and how long) and the browser Performance panel. React 19.2+ adds React tracks to Chrome's Performance panel. For user-facing latency, check Interaction to Next Paint (INP) and Largest Contentful Paint (LCP).
- Write down the measurement before and after the change in the PR. Do not claim a speed-up without one.
## 1. Let React Compiler memoise when it is enabled
With the compiler on, do not add new `memo`/`useMemo`/`useCallback` for performance. If a component still re-renders too much, check the compiler's output (DevTools "Memo ✨" badge) and fix the code it bailed out on.
## 2. Without the compiler, memoise surgically
- Wrap a component in `memo` only when the Profiler shows it re-rendering often with the same props and its render is expensive.
- `memo` works only if props are referentially stable. Then stabilise callbacks with `useCallback` and objects with `useMemo`, or move constant objects outside the component. Inline objects and arrays in JSX are harmless unless they are passed to a memoised child or used as a hook dependency.
- Keep state as close as possible to where it is used, and split large contexts (or pass a stable value), so one update does not re-render the whole tree.
## 3. Keep interactions responsive
- Mark non-urgent updates as transitions (`startTransition`/`useTransition`), or defer an expensive derived view with `useDeferredValue`, so typing stays responsive.
- For network or very expensive work triggered by input, debounce or throttle the call (typically 200–500 ms) and cancel stale requests with `AbortController`.
```tsx
import { memo, useDeferredValue, useState } from "react";
const Results = memo(function Results({ query, items }: { query: string; items: string[] }) {
const q = query.toLowerCase();
const filtered = items.filter((item) => item.toLowerCase().includes(q));
return <ul>{filtered.map((item) => <li key={item}>{item}</li>)}</ul>;
});
export function SearchableList({ items }: { items: string[] }) {
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query); // input updates first, the list catches up
return (
<>
<label>
Search <input value={query} onChange={(e) => setQuery(e.target.value)} />
</label>
<Results query={deferredQuery} items={items} />
</>
);
}
```
## 4. Render less: virtualise long lists
For lists or tables with many rows (typically hundreds or more, as measured), render only the visible rows with a virtualisation library (for example TanStack Virtual or react-window). Keep keys stable and unique (never array indexes for reorderable data). Preserve accessibility: keep semantic list or table roles, and make sure keyboard navigation and find-in-page expectations are acceptable.
## 5. Ship less JavaScript
- Split at route level first; most frameworks do this automatically. Then lazy-load heavy, rarely used components (editors, charts, maps) with `React.lazy` + `<Suspense fallback>`:
```tsx
const ChartPanel = lazy(() => import("./ChartPanel"));
```
- Check bundle composition with the bundler's analyzer, and replace or tree-shake large dependencies before micro-optimising renders.
- In Next.js, keep components as Server Components where possible, so their code is not sent to the client.
## 6. Move heavy CPU work off the main thread
Parsing large files, image processing, diffing or crypto that blocks the main thread for more than about 50 ms (a "long task") belongs in a Web Worker, or on the server. Pass data with `postMessage` (transferables for large buffers), and show progress in the UI.
## Things not to do
- Do not add `memo`/`useMemo`/`useCallback` everywhere "just in case". Do not use array indexes as keys for dynamic lists. Do not store derived data in state. Do not optimise without a profile.
## Verify before finishing
- Re-run the same Profiler or Performance recording on a production build and compare render counts and durations, or INP.
- Run tests and the type checker. Confirm virtualised lists remain keyboard and screen-reader usable.
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 .
Users report that typing in a filter box lags on a page that renders a long product table, and the developer asks Cursor to fix it.
ProductTable.tsx renders 5,000 rows and filters them on every keystroke from a controlled input in the same component. The Profiler shows each keystroke re-rendering all rows (~180 ms). React 19.2, no compiler, Vite.
Illustrative; not a recorded model run. A plan that starts from the recorded profile. The input stays urgent while the filtered table renders from useDeferredValue(query), and the table is virtualised (for example TanStack Virtual) so only visible rows render, with stable keys. A memoised row component gets stable props. The answer asks for a before/after Profiler recording on a production build and does not invent a speed-up number. Accessibility of the virtualised table is checked.
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-performance-optimization.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 Performance Optimization: Measure First, Then Memo, Defer, Virtualise and Split project conventions"
globs: "**/*"
alwaysApply: false
---
# React Performance Optimization
Applies to: React client UI where rendering, interaction latency (INP) or bundle size is a measured problem.
Version baseline: checked against the React 19 docs (including React Compiler 1.0 and React 19.2 Performance Tracks). Read the `react` version, whether React Compiler is enabled, and the framework (Next.js, Vite, Remix) before choosing a technique.
## 0. Measure before and after
- Reproduce the slowness in a production build. Development builds are much slower and run StrictMode double renders.
- Record it with the React DevTools Profiler (which components rendered, why, and how long) and the browser Performance panel. React 19.2+ adds React tracks to Chrome's Performance panel. For user-facing latency, check Interaction to Next Paint (INP) and Largest Contentful Paint (LCP).
- Write down the measurement before and after the change in the PR. Do not claim a speed-up without one.
## 1. Let React Compiler memoise when it is enabled
With the compiler on, do not add new `memo`/`useMemo`/`useCallback` for performance. If a component still re-renders too much, check the compiler's output (DevTools "Memo ✨" badge) and fix the code it bailed out on.
## 2. Without the compiler, memoise surgically
- Wrap a component in `memo` only when the Profiler shows it re-rendering often with the same props and its render is expensive.
- `memo` works only if props are referentially stable. Then stabilise callbacks with `useCallback` and objects with `useMemo`, or move constant objects outside the component. Inline objects and arrays in JSX are harmless unless they are passed to a memoised child or used as a hook dependency.
- Keep state as close as possible to where it is used, and split large contexts (or pass a stable value), so one update does not re-render the whole tree.
## 3. Keep interactions responsive
- Mark non-urgent updates as transitions (`startTransition`/`useTransition`), or defer an expensive derived view with `useDeferredValue`, so typing stays responsive.
- For network or very expensive work triggered by input, debounce or throttle the call (typically 200–500 ms) and cancel stale requests with `AbortController`.
```tsx
import { memo, useDeferredValue, useState } from "react";
const Results = memo(function Results({ query, items }: { query: string; items: string[] }) {
const q = query.toLowerCase();
const filtered = items.filter((item) => item.toLowerCase().includes(q));
return <ul>{filtered.map((item) => <li key={item}>{item}</li>)}</ul>;
});
export function SearchableList({ items }: { items: string[] }) {
const [query, setQuery] = useState("");
const deferredQuery = useDeferredValue(query); // input updates first, the list catches up
return (
<>
<label>
Search <input value={query} onChange={(e) => setQuery(e.target.value)} />
</label>
<Results query={deferredQuery} items={items} />
</>
);
}
```
## 4. Render less: virtualise long lists
For lists or tables with many rows (typically hundreds or more, as measured), render only the visible rows with a virtualisation library (for example TanStack Virtual or react-window). Keep keys stable and unique (never array indexes for reorderable data). Preserve accessibility: keep semantic list or table roles, and make sure keyboard navigation and find-in-page expectations are acceptable.
## 5. Ship less JavaScript
- Split at route level first; most frameworks do this automatically. Then lazy-load heavy, rarely used components (editors, charts, maps) with `React.lazy` + `<Suspense fallback>`:
```tsx
const ChartPanel = lazy(() => import("./ChartPanel"));
```
- Check bundle composition with the bundler's analyzer, and replace or tree-shake large dependencies before micro-optimising renders.
- In Next.js, keep components as Server Components where possible, so their code is not sent to the client.
## 6. Move heavy CPU work off the main thread
Parsing large files, image processing, diffing or crypto that blocks the main thread for more than about 50 ms (a "long task") belongs in a Web Worker, or on the server. Pass data with `postMessage` (transferables for large buffers), and show progress in the UI.
## Things not to do
- Do not add `memo`/`useMemo`/`useCallback` everywhere "just in case". Do not use array indexes as keys for dynamic lists. Do not store derived data in state. Do not optimise without a profile.
## Verify before finishing
- Re-run the same Profiler or Performance recording on a production build and compare render counts and durations, or INP.
- Run tests and the type checker. Confirm virtualised lists remain keyboard and screen-reader usable.
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.