AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

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.

Original source
vercel-labs
License
MIT
Pinned revision
1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read vercel-labs--vercel-react-best-practices at revision 1a2c79d4e6c4a2283dc2c614b6538cbe1ed5ca62, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 75

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

  1. Eliminating Waterfalls — CRITICAL
  2. Bundle Size Optimization — CRITICAL
  3. Server-Side Performance — HIGH
  4. Client-Side Data Fetching — MEDIUM-HIGH
  5. Re-render Optimization — MEDIUM
  6. Rendering Performance — MEDIUM
  7. JavaScript Performance — LOW-MEDIUM
  8. 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.ts files for their deep import paths. Importing from lucide-react/dist/esm/icons/check resolves to an implicit any type, causing errors under strict or noImplicitAny. Prefer optimizePackageImports when 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