vercel react best practices
React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
Documentation & Preview
React Best Practices
Version 0.1.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 at Vercel. 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
- 1.1 Defer Await Until Needed
- 1.2 Dependency-Based Parallelization
- 1.3 Prevent Waterfall Chains in API Routes
- 1.4 Promise.all() for Independent Operations
- 1.5 Strategic Suspense Boundaries
- Bundle Size Optimization — CRITICAL
- 2.1 Avoid Barrel File Imports
- 2.2 Conditional Module Loading
- 2.3 Defer Non-Critical Third-Party Libraries
- 2.4 Dynamic Imports for Heavy Components
- 2.5 Preload Based on User Intent
- Server-Side Performance — HIGH
- 3.1 Cross-Request LRU Caching
- 3.2 Minimize Serialization at RSC Boundaries
- 3.3 Parallel Data Fetching with Component Composition
- 3.4 Per-Request Deduplication with React.cache()
- 3.5 Use after() for Non-Blocking Operations
- Client-Side Data Fetching — MEDIUM-HIGH
- 4.1 Deduplicate Global Event Listeners
- 4.2 Use SWR for Automatic Deduplication
- Re-render Optimization — MEDIUM
- 5.1 Defer State Reads to Usage Point
- 5.2 Extract to Memoized Components
- 5.3 Narrow Effect Dependencies
- 5.4 Subscribe to Derived State
- 5.5 Use Functional setState Updates
- 5.6 Use Lazy State Initialization
- 5.7 Use Transitions for Non-Urgent Updates
- 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 Use Activity Component for Show/Hide
- 6.7 Use Explicit Conditional Rendering
- JavaScript Performance — LOW-MEDIUM
- 7.1 Batch DOM CSS Changes
- 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 Early Length Check for Array Comparisons
- 7.8 Early Return from Functions
- 7.9 Hoist RegExp Creation
- 7.10 Use Loop for Min/Max Instead of Sort
- 7.11 Use Set/Map for O(1) Lookups
- 7.12 Use toSorted() Instead of sort() for Immutability
- Advanced Patterns — LOW
- 8.1 Store Event Handlers in Refs
- 8.2 useLatest for Stable Callback Refs
---
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 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.
1.2 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)
}
})Reference: https://github.com/shuding/better-all
1.3 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.4 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.5 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 p