Skill: react-best-practices
Base directory: /home/hetav/.claude/skills/react-best-practices
name: vercel-react-best-practices description: 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. license: MIT metadata: author: vercel version: "1.0.0"
Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
When to Apply
Reference these guidelines when:
- •Writing new React components or Next.js pages
- •Implementing data fetching (client or server-side)
- •Reviewing code for performance issues
- •Refactoring existing React/Next.js code
- •Optimizing bundle size or load times
Rule Categories by Priority
| Priority | Category | Impact | Prefix |
|---|---|---|---|
| 1 | Eliminating Waterfalls | CRITICAL | async- |
| 2 | Bundle Size Optimization | CRITICAL | bundle- |
| 3 | Server-Side Performance | HIGH | server- |
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | client- |
| 5 | Re-render Optimization | MEDIUM | rerender- |
| 6 | Rendering Performance | MEDIUM | rendering- |
| 7 | JavaScript Performance | LOW-MEDIUM | js- |
| 8 | Advanced Patterns | LOW | advanced- |
Quick Reference
1. Eliminating Waterfalls (CRITICAL)
- •
async-defer-await- Move await into branches where actually used - •
async-parallel- Use Promise.all() for independent operations - •
async-dependencies- Use better-all for partial dependencies - •
async-api-routes- Start promises early, await late in API routes - •
async-suspense-boundaries- Use Suspense to stream content
2. Bundle Size Optimization (CRITICAL)
- •
bundle-barrel-imports- Import directly, avoid barrel files - •
bundle-dynamic-imports- Use next/dynamic for heavy components - •
bundle-defer-third-party- Load analytics/logging after hydration - •
bundle-conditional- Load modules only when feature is activated - •
bundle-preload- Preload on hover/focus for perceived speed
3. Server-Side Performance (HIGH)
- •
server-cache-react- Use React.cache() for per-request deduplication - •
server-cache-lru- Use LRU cache for cross-request caching - •
server-serialization- Minimize data passed to client components - •
server-parallel-fetching- Restructure components to parallelize fetches - •
server-after-nonblocking- Use after() for non-blocking operations
4. Client-Side Data Fetching (MEDIUM-HIGH)
- •
client-swr-dedup- Use SWR for automatic request deduplication - •
client-event-listeners- Deduplicate global event listeners
5. Re-render Optimization (MEDIUM)
- •
rerender-defer-reads- Don't subscribe to state only used in callbacks - •
rerender-memo- Extract expensive work into memoized components - •
rerender-dependencies- Use primitive dependencies in effects - •
rerender-derived-state- Subscribe to derived booleans, not raw values - •
rerender-functional-setstate- Use functional setState for stable callbacks - •
rerender-lazy-state-init- Pass function to useState for expensive values - •
rerender-transitions- Use startTransition for non-urgent updates
6. Rendering Performance (MEDIUM)
- •
rendering-animate-svg-wrapper- Animate div wrapper, not SVG element - •
rendering-content-visibility- Use content-visibility for long lists - •
rendering-hoist-jsx- Extract static JSX outside components - •
rendering-svg-precision- Reduce SVG coordinate precision - •
rendering-hydration-no-flicker- Use inline script for client-only data - •
rendering-activity- Use Activity component for show/hide - •
rendering-conditional-render- Use ternary, not && for conditionals
7. JavaScript Performance (LOW-MEDIUM)
- •
js-batch-dom-css- Group CSS changes via classes or cssText - •
js-index-maps- Build Map for repeated lookups - •
js-cache-property-access- Cache object properties in loops - •
js-cache-function-results- Cache function results in module-level Map - •
js-cache-storage- Cache localStorage/sessionStorage reads - •
js-combine-iterations- Combine multiple filter/map into one loop - •
js-length-check-first- Check array length before expensive comparison - •
js-early-exit- Return early from functions - •
js-hoist-regexp- Hoist RegExp creation outside loops - •
js-min-max-loop- Use loop for min/max instead of sort - •
js-set-map-lookups- Use Set/Map for O(1) lookups - •
js-tosorted-immutable- Use toSorted() for immutability
8. Advanced Patterns (LOW)
- •
advanced-event-handler-refs- Store event handlers in refs - •
advanced-use-latest- useLatest for stable callback refs
Detailed Rules (Critical & High Impact)
1. Promise.all() for Independent Operations (async-parallel)
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()]);
2. Avoid Barrel File Imports (bundle-barrel-imports)
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 (imports only what you need):
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'; // Loads only 3 modules (~2KB vs ~1MB) import Button from '@mui/material/Button'; import TextField from '@mui/material/TextField'; // Loads only what you use
Alternative (Next.js 13.5+):
// next.config.js - use optimizePackageImports
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material'],
},
};
// Then you can keep the ergonomic barrel imports:
import { Check, X, Menu } from 'lucide-react';
// Automatically transformed to direct imports at build time
Direct imports 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: How we optimized package imports in Next.js
3. Dynamic Imports for Heavy Components (bundle-dynamic-imports)
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} />;
}
4. Per-Request Deduplication with React.cache() (server-cache-react)
Use React.cache() for server-side request deduplication. Authentication and database queries benefit most.
Usage:
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 },
});
});
Within a single request, multiple calls to getCurrentUser() execute the query only once.
Avoid inline objects as arguments:
React.cache() uses shallow equality (Object.is) to determine cache hits. Inline objects create new references each call, preventing cache hits.
Incorrect (always cache miss):
const getUser = cache(async (params: { uid: number }) => {
return await db.user.findUnique({ where: { id: params.uid } });
});
// Each call creates new object, never hits cache
getUser({ uid: 1 });
getUser({ uid: 1 }); // Cache miss, runs query again
Correct (cache hit):
const getUser = cache(async (uid: number) => {
return await db.user.findUnique({ where: { id: uid } });
});
// Primitive args use value equality
getUser(1);
getUser(1); // Cache hit, returns cached result
If you must pass objects, pass the same reference:
const params = { uid: 1 };
getUser(params); // Query runs
getUser(params); // Cache hit (same reference)
Next.js-Specific Note:
In Next.js, the fetch API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need React.cache() for fetch calls. However, React.cache() is still essential for other async tasks:
- •Database queries (Prisma, Drizzle, etc.)
- •Heavy computations
- •Authentication checks
- •File system operations
- •Any non-fetch async work
Use React.cache() to deduplicate these operations across your component tree.
Reference: React.cache documentation
5. Parallel Data Fetching with Component Composition (server-parallel-fetching)
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
Incorrect (Sidebar waits for Page's fetch to complete):
export default async function Page() {
const header = await fetchHeader();
return (
<div>
<div>{header}</div>
<Sidebar />
</div>
);
}
async function Sidebar() {
const items = await fetchSidebarItems();
return <nav>{items.map(renderItem)}</nav>;
}
Correct (both fetch simultaneously):
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>
);
}
Alternative with children prop:
async function Header() {
const data = await fetchHeader();
return <div>{data}</div>;
}
async function Sidebar() {
const items = await fetchSidebarItems();
return <nav>{items.map(renderItem)}</nav>;
}
function Layout({ children }: { children: ReactNode }) {
return (
<div>
<Header />
{children}
</div>
);
}
export default function Page() {
return (
<Layout>
<Sidebar />
</Layout>
);
}