AGENTS.md
React Best Practices
Version 1.0.0
Vercel Engineering
January 2026
Note:
This document is mainly for agents and LLMs to follow when maintaining,
generating, or refactoring React and Next.js codebases. Humans
may also find it useful, but guidance here is optimized for automation
and consistency by AI-assisted workflows.
Abstract
Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.
Table of Contents
- Eliminating Waterfalls — CRITICAL
- Bundle Size Optimization — CRITICAL
- Server-Side Performance — HIGH
- 3.1 Authenticate Server Actions Like API Routes
- 3.2 Avoid Duplicate Serialization in RSC Props
- 3.3 Avoid Shared Module State for Request Data
- 3.4 Cross-Request LRU Caching
- 3.5 Hoist Static I/O to Module Level
- 3.6 Minimize Serialization at RSC Boundaries
- 3.7 Parallel Data Fetching with Component Composition
- 3.8 Parallel Nested Data Fetching
- 3.9 Per-Request Deduplication with React.cache()
- 3.10 Use after() for Non-Blocking Operations
- Client-Side Data Fetching — MEDIUM-HIGH
- Re-render Optimization — MEDIUM
- 5.1 Calculate Derived State During Rendering
- 5.2 Defer State Reads to Usage Point
- 5.3 Do not wrap a simple expression with a primitive result type in useMemo
- 5.4 Don't Define Components Inside Components
- 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant
- 5.6 Extract to Memoized Components
- 5.7 Narrow Effect Dependencies
- 5.8 Put Interaction Logic in Event Handlers
- 5.9 Split Combined Hook Computations
- 5.10 Subscribe to Derived State
- 5.11 Use Functional setState Updates
- 5.12 Use Lazy State Initialization
- 5.13 Use Transitions for Non-Urgent Updates
- 5.14 Use useDeferredValue for Expensive Derived Renders
- 5.15 Use useRef for Transient Values
- Rendering Performance — MEDIUM
- 6.1 Animate SVG Wrapper Instead of SVG Element
- 6.2 CSS content-visibility for Long Lists
- 6.3 Hoist Static JSX Elements
- 6.4 Optimize SVG Precision
- 6.5 Prevent Hydration Mismatch Without Flickering
- 6.6 Suppress Expected Hydration Mismatches
- 6.7 Use Activity Component for Show/Hide
- 6.8 Use defer or async on Script Tags
- 6.9 Use Explicit Conditional Rendering
- 6.10 Use React DOM Resource Hints
- 6.11 Use useTransition Over Manual Loading States
- JavaScript Performance — LOW-MEDIUM
- 7.1 Avoid Layout Thrashing
- 7.2 Build Index Maps for Repeated Lookups
- 7.3 Cache Property Access in Loops
- 7.4 Cache Repeated Function Calls
- 7.5 Cache Storage API Calls
- 7.6 Combine Multiple Array Iterations
- 7.7 Defer Non-Critical Work with requestIdleCallback
- 7.8 Early Length Check for Array Comparisons
- 7.9 Early Return from Functions
- 7.10 Hoist RegExp Creation
- 7.11 Use flatMap to Map and Filter in One Pass
- 7.12 Use Loop for Min/Max Instead of Sort
- 7.13 Use Set/Map for O(1) Lookups
- 7.14 Use toSorted() Instead of sort() for Immutability
- Advanced Patterns — LOW
1. Eliminating Waterfalls
Impact: CRITICAL
Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
1.1 Check Cheap Conditions Before Async Flags
Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)
When a branch uses await for a flag or remote value and also requires a cheap synchronous condition (local props, request metadata, already-loaded state), evaluate the cheap condition first. Otherwise you pay for the async call even when the compound condition can never be true.
This is a specialization of Defer Await Until Needed for flag && cheapCondition style checks.
Incorrect:
const someFlag = await getFlag()
if (someFlag && someCondition) {
// ...
}
Correct:
if (someCondition) {
const someFlag = await getFlag()
if (someFlag) {
// ...
}
}
This matters when getFlag hits the network, a feature-flag service, or React.cache / DB work: skipping it when someCondition is false removes that cost on the cold path.
Keep the original order if someCondition is expensive, depends on the flag, or you must run side effects in a fixed order.
1.2 Defer Await Until Needed
Impact: HIGH (avoids blocking unused code paths)
Move await operations into the branches where they're actually used to avoid blocking code paths that don't need them.
Incorrect: blocks both branches
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true }
}
// Only this branch uses userData
return processUserData(userData)
}
Correct: only blocks when needed
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true }
}
// Fetch only when needed
const userData = await fetchUserData(userId)
return processUserData(userData)
}
Another example: early return optimization
// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
const permissions = await fetchPermissions(userId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
return await updateResourceData(resource, permissions)
}
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
For await getFlag() combined with a cheap synchronous guard (flag && someCondition), see Check Cheap Conditions Before Async Flags.
1.3 Dependency-Based Parallelization
Impact: CRITICAL (2-10× improvement)
For operations with partial dependencies, use better-all to maximize parallelism. It automatically starts each task at the earliest possible moment.
Incorrect: profile waits for config unnecessarily
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
Correct: config and profile run in parallel
import { all } from 'better-all'
const { user, config, profile } = await all({
async user() { return fetchUser() },
async config() { return fetchConfig() },
async profile() {
return fetchProfile((await this.$.user).id)
}
})
Alternative without extra dependencies:
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
We can also create all the promises first, and do Promise.all() at the end.
Reference: https://github.com/shuding/better-all
1.4 Prevent Waterfall Chains in API Routes
Impact: CRITICAL (2-10× improvement)
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
Incorrect: config waits for auth, data waits for both
export async function GET(request: Request) {
const session = await auth()
const config = await fetchConfig()
const data = await fetchData(session.user.id)
return Response.json({ data, config })
}
Correct: auth and config start immediately
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
const session = await sessionPromise
const [config, data] = await Promise.all([
configPromise,
fetchData(session.user.id)
])
return Response.json({ data, config })
}
For operations with more complex dependency chains, use better-all to automatically maximize parallelism (see Dependency-Based Parallelization).
1.5 Promise.all() for Independent Operations
Impact: CRITICAL (2-10× improvement)
When async operations have no interdependencies, execute them concurrently using Promise.all().
Incorrect: sequential execution, 3 round trips
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
Correct: parallel execution, 1 round trip
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
1.6 Strategic Suspense Boundaries
Impact: HIGH (faster initial paint)
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
Incorrect: wrapper blocked by data fetching
async function Page() {
const data = await fetchData() // Blocks entire page
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<DataDisplay data={data} />
</div>
<div>Footer</div>
</div>
)
}
The entire layout waits for data even though only the middle section needs it.
Correct: wrapper shows immediately, data streams in
function Page() {
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<div>
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
</div>
<div>Footer</div>
</div>
)
}
async function DataDisplay() {
const data = await fetchData() // Only blocks this component
return <div>{data.content}</div>
}
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
Alternative: share promise across components
function Page() {
// Start fetch immediately, but don't await
const dataPromise = fetchData()
return (
<div>
<div>Sidebar</div>
<div>Header</div>
<Suspense fallback={<Skeleton />}>
<DataDisplay dataPromise={dataPromise} />
<DataSummary dataPromise={dataPromise} />
</Suspense>
<div>Footer</div>
</div>
)
}
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Unwraps the promise
return <div>{data.content}</div>
}
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
const data = use(dataPromise) // Reuses the same promise
return <div>{data.summary}</div>
}
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
When NOT to use this pattern:
-
Critical data needed for layout decisions (affects positioning)
-
SEO-critical content above the fold
-
Small, fast queries where suspense overhead isn't worth it
-
When you want to avoid layout shift (loading → content jump)
Trade-off: Faster initial paint vs potential layout shift. Choose based on your UX priorities.
2. Bundle Size Optimization
Impact: CRITICAL
Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
2.1 Avoid Barrel File Imports
Impact: CRITICAL (200-800ms import cost, slow builds)
Import directly from source files instead of barrel files to avoid loading thousands of unused modules. Barrel files are entry points that re-export multiple modules (e.g., index.js that does export * from './module').
Popular icon and component libraries can have up to 10,000 re-exports in their entry file. For many React packages, it takes 200-800ms just to import them, affecting both development speed and production cold starts.
Why tree-shaking doesn't help: When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
Incorrect: imports entire library
import { Check, X, Menu } from 'lucide-react'
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start
import { Button, TextField } from '@mui/material'
// Loads 2,225 modules, takes ~4.2s extra in dev
Correct - Next.js 13.5+ (recommended):
// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from 'lucide-react'
// Full TypeScript support, no manual path wrangling
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
Correct - Direct imports (non-Next.js projects):
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
TypeScript warning: Some libraries (notably
lucide-react) don't ship.d.tsfiles for their deep import paths. Importing fromlucide-react/dist/esm/icons/checkresolves to an implicitanytype, causing errors understrictornoImplicitAny. PreferoptimizePackageImportswhen available, or verify the library exports types for its subpaths before using direct imports.
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
Libraries commonly affected: lucide-react, @mui/material, @mui/icons-material, @tabler/icons-react, react-icons, @headlessui/react, @radix-ui/react-*, lodash, ramda, date-fns, rxjs, react-use.
Reference: https://vercel.com/blog/how-we-optimized-package-imports-in-next-js
2.2 Conditional Module Loading
Impact: HIGH (loads large data only when needed)
Load large data or modules only when a feature is activated.
Example: lazy-load animation frames
function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
const [frames, setFrames] = useState<Frame[] | null>(null)
useEffect(() => {
if (enabled && !frames && typeof window !== 'undefined') {
import('./animation-frames.js')
.then(mod => setFrames(mod.frames))
.catch(() => setEnabled(false))
}
}, [enabled, frames, setEnabled])
if (!frames) return <Skeleton />
return <Canvas frames={frames} />
}
The typeof window !== 'undefined' check prevents bundling this module for SSR, optimizing server bundle size and build speed.
2.3 Defer Non-Critical Third-Party Libraries
Impact: MEDIUM (loads after hydration)
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
Incorrect: blocks initial bundle
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
Correct: loads after hydration
import dynamic from 'next/dynamic'
const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
2.4 Dynamic Imports for Heavy Components
Impact: CRITICAL (directly affects TTI and LCP)
Use next/dynamic to lazy-load large components not needed on initial render.
Incorrect: Monaco bundles with main chunk ~300KB
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
Correct: Monaco loads on demand
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
() => import('./monaco-editor').then(m => m.MonacoEditor),
{ ssr: false }
)
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
2.5 Prefer Statically Analyzable Paths
Impact: HIGH (avoids accidental broad bundles and file traces)
Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with import() or reading files in server/build code.
When analysis becomes too broad, the cost is real:
-
Larger server bundles
-
Slower builds
-
Worse cold starts
-
More memory use
Incorrect: the bundler cannot tell what may be imported
const PAGE_MODULES = {
home: './pages/home',
settings: './pages/settings',
} as const
const Page = await import(PAGE_MODULES[pageName])
Correct: use an explicit map of allowed modules
const PAGE_MODULES = {
home: () => import('./pages/home'),
settings: () => import('./pages/settings'),
} as const
const Page = await PAGE_MODULES[pageName]()
Incorrect: a 2-value enum still hides the final path from static analysis
const baseDir = path.join(process.cwd(), 'content/' + contentKind)
Correct: make each final path literal at the callsite
const baseDir =
kind === ContentKind.Blog
? path.join(process.cwd(), 'content/blog')
: path.join(process.cwd(), 'content/docs')
In Next.js server code, this matters for output file tracing too. path.join(process.cwd(), someVar) can widen the traced file set because Next.js statically analyze import, require, and fs usage.
Reference: https://nextjs.org/docs/app/api-reference/config/next-config-js/output, https://nextjs.org/learn/seo/dynamic-imports, https://vite.dev/guide/features.html, https://esbuild.github.io/api/, https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars, https://webpack.js.org/guides/dependency-management/
2.6 Preload Based on User Intent
Impact: MEDIUM (reduces perceived latency)
Preload heavy bundles before they're needed to reduce perceived latency.
Example: preload on hover/focus
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== 'undefined') {
void import