| name | react-best-practices |
| description | React and Next.js performance optimization patterns. Use BEFORE implementing any React code to ensure best practices are followed. |
React Best Practices
Version 1.0.0
Source: Vercel Engineering (vercel-labs/agent-skills)
Note:
This document is for agents and LLMs to follow when maintaining,
generating, or refactoring React and Next.js codebases. Contains 40+ rules across 8 categories, prioritized by impact.
How to Use This Skill
Before implementing ANY React/Next.js code:
- Review the relevant sections based on what you're building
- Apply the patterns as you write code
- Use the "Incorrect" vs "Correct" examples as templates
Priority order: Eliminating Waterfalls > Bundle Size > Server-Side > Client-Side > Re-renders > Rendering > JS Perf > Advanced
Quick Reference: Critical Rules
Top 5 Rules (Always Apply)
- Promise.all() for independent operations - Never sequential awaits for independent data
- Avoid barrel file imports - Import directly from source files
- Dynamic imports for heavy components - Lazy-load Monaco, charts, etc.
- Parallel data fetching with component composition - Structure RSC for parallelism
- Minimize serialization at RSC boundaries - Only pass needed fields to client
1. Eliminating Waterfalls
Impact: CRITICAL - Waterfalls are the #1 performance killer.
1.1 Defer Await Until Needed
Move await into branches where actually used.
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) return { skipped: true }
return processUserData(userData)
}
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) return { skipped: true }
const userData = await fetchUserData(userId)
return processUserData(userData)
}
1.2 Promise.all() for Independent Operations
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
1.3 Strategic Suspense Boundaries
async function Page() {
const data = await fetchData()
return (
<div>
<Sidebar />
<DataDisplay data={data} />
<Footer />
</div>
)
}
function Page() {
return (
<div>
<Sidebar />
<Suspense fallback={<Skeleton />}>
<DataDisplay />
</Suspense>
<Footer />
</div>
)
}
2. Bundle Size Optimization
Impact: CRITICAL - Reduces TTI and LCP.
2.1 Avoid Barrel File Imports
import { Check, X, Menu } from 'lucide-react'
import Check from 'lucide-react/dist/esm/icons/check'
import X from 'lucide-react/dist/esm/icons/x'
import Menu from 'lucide-react/dist/esm/icons/menu'
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
2.2 Dynamic Imports for Heavy Components
import { MonacoEditor } from './monaco-editor'
import dynamic from 'next/dynamic'
const MonacoEditor = dynamic(
() => import('./monaco-editor').then(m => m.MonacoEditor),
{ ssr: false }
)
2.3 Defer Non-Critical Libraries
import { Analytics } from '@vercel/analytics/react'
import dynamic from 'next/dynamic'
const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
2.4 Preload on User Intent
function EditorButton({ onClick }: { onClick: () => void }) {
const preload = () => {
if (typeof window !== 'undefined') {
void import('./monaco-editor')
}
}
return (
<button onMouseEnter={preload} onFocus={preload} onClick={onClick}>
Open Editor
</button>
)
}
3. Server-Side Performance
Impact: HIGH
3.1 Minimize Serialization at RSC Boundaries
async function Page() {
const user = await fetchUser()
return <Profile user={user} />
}
async function Page() {
const user = await fetchUser()
return <Profile name={user.name} avatar={user.avatar} />
}
3.2 Parallel Data Fetching with Component Composition
export default async function Page() {
const header = await fetchHeader()
return (
<div>
<div>{header}</div>
<Sidebar />
</div>
)
}
async function Header() {
const data = await fetchHeader()
return <div>{data}</div>
}
async function Sidebar() {
const items = await fetchSidebarItems()
return <nav>{items.map(renderItem)}</nav>
}
export default function Page() {
return (
<div>
<Header />
<Sidebar />
</div>
)
}
3.3 Per-Request Deduplication with React.cache()
import { cache } from 'react'
export const getCurrentUser = cache(async () => {
const session = await auth()
if (!session?.user?.id) return null
return await db.user.findUnique({ where: { id: session.user.id } })
})
3.4 Use after() for Non-Blocking Operations
import { after } from 'next/server'
export async function POST(request: Request) {
await updateDatabase(request)
after(async () => {
const userAgent = (await headers()).get('user-agent')
logUserAction({ userAgent })
})
return Response.json({ status: 'success' })
}
4. Client-Side Data Fetching
Impact: MEDIUM-HIGH
4.1 Use SWR for Automatic Deduplication
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users').then(r => r.json()).then(setUsers)
}, [])
}
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
5. Re-render Optimization
Impact: MEDIUM
5.1 Use Functional setState Updates
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items])
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, [])
5.2 Use Lazy State Initialization
const [settings] = useState(JSON.parse(localStorage.getItem('settings') || '{}'))
const [settings] = useState(() => {
const stored = localStorage.getItem('settings')
return stored ? JSON.parse(stored) : {}
})
5.3 Use Transitions for Non-Urgent Updates
import { startTransition } from 'react'
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => {
startTransition(() => setScrollY(window.scrollY))
}
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
5.4 Narrow Effect Dependencies
useEffect(() => {
console.log(user.id)
}, [user])
useEffect(() => {
console.log(user.id)
}, [user.id])
6. Rendering Performance
Impact: MEDIUM
6.1 CSS content-visibility for Long Lists
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
6.2 Hoist Static JSX Elements
function Container() {
return loading && <div className="animate-pulse h-20 bg-gray-200" />
}
const loadingSkeleton = <div className="animate-pulse h-20 bg-gray-200" />
function Container() {
return loading && loadingSkeleton
}
6.3 Animate SVG Wrapper, Not SVG Element
<svg className="animate-spin">...</svg>
<div className="animate-spin">
<svg>...</svg>
</div>
7. JavaScript Performance
Impact: LOW-MEDIUM
7.1 Build Index Maps for Repeated Lookups
items.filter(item => allowedIds.includes(item.id))
const allowedSet = new Set(allowedIds)
items.filter(item => allowedSet.has(item.id))
7.2 Use toSorted() Instead of sort()
const sorted = users.sort((a, b) => a.name.localeCompare(b.name))
const sorted = users.toSorted((a, b) => a.name.localeCompare(b.name))
7.3 Early Return from Functions
function validateUsers(users: User[]) {
let hasError = false
for (const user of users) {
if (!user.email) hasError = true
}
return hasError ? { valid: false } : { valid: true }
}
function validateUsers(users: User[]) {
for (const user of users) {
if (!user.email) return { valid: false, error: 'Email required' }
}
return { valid: true }
}
8. Advanced Patterns
Impact: LOW
8.1 useEffectEvent for Stable Callbacks
import { useEffectEvent } from 'react'
function useWindowEvent(event: string, handler: () => void) {
const onEvent = useEffectEvent(handler)
useEffect(() => {
window.addEventListener(event, onEvent)
return () => window.removeEventListener(event, onEvent)
}, [event])
}
Checklist Before Implementation
References