vercel-react-best-practices
Vercel React best practices for rendering performance, bundle efficiency, and scalable component architecture.
Install
npx skills add https://github.com/vercel-labs/agent-skills --skill vercel-react-best-practicesReact 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:
Correct:
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
Correct: only blocks when needed
Another example: early return optimization
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
Correct: config and profile run in parallel
Alternative without extra dependencies:
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
Correct: auth and config start immediately
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
Correct: parallel execution, 1 round trip
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
The entire layout waits for data even though only the middle section needs it.
Correct: wrapper shows immediately, data streams in
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
Alternative: share promise across components
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
Correct - Next.js 13.5+ (recommended):
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):
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
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
Correct: loads after hydration
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
Correct: Monaco loads on demand
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
Correct: use an explicit map of allowed modules
Incorrect: a 2-value enum still hides the final path from static analysis
Correct: make each final path literal at the callsite
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
Example: preload when feature flag is enabled
The typeof window !== 'undefined' check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
3. Server-Side Performance
Impact: HIGH
Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
3.1 Authenticate Server Actions Like API Routes
Impact: CRITICAL (prevents unauthorized access to server mutations)
Server Actions (functions with "use server") are exposed as public endpoints, just like API routes. Always verify authentication and authorization inside each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
Incorrect: no authentication check
Correct: authentication inside the action
With input validation:
Reference: https://nextjs.org/docs/app/guides/authentication
3.2 Avoid Duplicate Serialization in RSC Props
Impact: LOW (reduces network payload by avoiding duplicate serialization)
RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (.toSorted(), .filter(), .map()) in client, not server.
Incorrect: duplicates array
Correct: sends 3 strings
Nested deduplication behavior:
Deduplication works recursively. Impact varies by data type:
string[],number[],boolean[]: HIGH impact - array + all primitives fully duplicatedobject[]: LOW impact - array duplicated, but nested objects deduplicated by reference
Operations breaking deduplication: create new references
- Arrays:
.toSorted(),.filter(),.map(),.slice(),[...arr] - Objects:
{...obj},Object.assign(),structuredClone(),JSON.parse(JSON.stringify())
More examples:
Exception: Pass derived data when transformation is expensive or client doesn't need original.
3.3 Avoid Shared Module State for Request Data
Impact: HIGH (prevents concurrency bugs and request data leaks)
For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
Treat module scope on the server as process-wide shared memory, not request-local state.
Incorrect: request data leaks across concurrent renders
If two requests overlap, request A can set currentUser, then request B overwrites it before request A finishes rendering Dashboard.
Correct: keep request data local to the render tree
Safe exceptions:
- Immutable static assets or config loaded once at module scope
- Shared caches intentionally designed for cross-request reuse and keyed correctly
- Process-wide singletons that do not store request- or user-specific mutable data
For static assets and config, see Hoist Static I/O to Module Level.
3.4 Cross-Request LRU Caching
Impact: HIGH (caches across requests)
React.cache() only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
Implementation:
Use when sequential user actions hit multiple endpoints needing the same data within seconds.
With Vercel's Fluid Compute: LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
In traditional serverless: Each invocation runs in isolation, so consider Redis for cross-process caching.
Reference: https://github.com/isaacs/node-lru-cache
3.5 Hoist Static I/O to Module Level
Impact: HIGH (avoids repeated file/network I/O per request)
When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
Incorrect: reads font file on every request
Correct: loads once at module initialization
Correct: synchronous fs at module level
Incorrect: reads config on every call
Correct: hoists config and template to module level
When to use this pattern:
- Loading fonts for OG image generation
- Loading static logos, icons, or watermarks
- Reading configuration files that don't change at runtime
- Loading email templates or other static templates
- Any static asset that's the same across all requests
When not to use this pattern:
- Assets that vary per request or user
- Files that may change during runtime (use caching with TTL instead)
- Large files that would consume too much memory if kept loaded
- Sensitive data that shouldn't persist in memory
With Vercel's Fluid Compute, module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
3.6 Minimize Serialization at RSC Boundaries
Impact: HIGH (reduces data transfer size)
The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so size matters a lot. Only pass fields that the client actually uses.
Incorrect: serializes all 50 fields
Correct: serializes only 1 field
3.7 Parallel Data Fetching with Component Composition
Impact: CRITICAL (eliminates server-side waterfalls)
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
Incorrect: Sidebar waits for Page's fetch to complete
Correct: both fetch simultaneously
Alternative with children prop:
3.8 Parallel Nested Data Fetching
Impact: CRITICAL (eliminates server-side waterfalls)
When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
Incorrect: a single slow item blocks all nested fetches
If one getChat(id) out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
Correct: each item chains its own nested fetch
Each item independently chains getChat → getUser, so a slow chat doesn't block author fetches for the others.
3.9 Per-Request Deduplication with React.cache()
Impact: MEDIUM (deduplicates within request)
Use React.cache() for server-side request deduplication. Authentication and database queries benefit most.
Usage:
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
Correct: cache hit
If you must pass objects, pass the 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: https://react.dev/reference/react/cache
3.10 Use after() for Non-Blocking Operations
Impact: MEDIUM (faster response times)
Use Next.js's after() to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
Incorrect: blocks response
Correct: non-blocking
The response is sent immediately while logging happens in the background.
Common use cases:
- Analytics tracking
- Audit logging
- Sending notifications
- Cache invalidation
- Cleanup tasks
Important notes:
after()runs even if the response fails or redirects- Works in Server Actions, Route Handlers, and Server Components
Reference: https://nextjs.org/docs/app/api-reference/functions/after
4. Client-Side Data Fetching
Impact: MEDIUM-HIGH
Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
4.1 Deduplicate Global Event Listeners
Impact: LOW (single listener for N components)
Use useSWRSubscription() to share global event listeners across component instances.
Incorrect: N instances = N listeners
When using the useKeyboardShortcut hook multiple times, each instance will register a new listener.
Correct: N instances = 1 listener
4.2 Use Passive Event Listeners for Scrolling Performance
Impact: MEDIUM (eliminates scroll delay caused by event listeners)
Add { passive: true } to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if preventDefault() is called, causing scroll delay.
Incorrect:
Correct:
Use passive when: tracking/analytics, logging, any listener that doesn't call preventDefault().
Don't use passive when: implementing custom swipe gestures, custom zoom controls, or any listener that needs preventDefault().
4.3 Use SWR for Automatic Deduplication
Impact: MEDIUM-HIGH (automatic deduplication)
SWR enables request deduplication, caching, and revalidation across component instances.
Incorrect: no deduplication, each instance fetches
Correct: multiple instances share one request
For immutable data:
For mutations:
Reference: https://swr.vercel.app
4.4 Version and Minimize localStorage Data
Impact: MEDIUM (prevents schema conflicts, reduces storage size)
Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
Incorrect:
Correct:
Store minimal fields from server responses:
Always wrap in try-catch: getItem() and setItem() throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
Benefits: Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
5. Re-render Optimization
Impact: MEDIUM
Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
5.1 Calculate Derived State During Rendering
Impact: MEDIUM (avoids redundant renders and state drift)
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
Incorrect: redundant state and effect
Correct: derive during render
Reference: https://react.dev/learn/you-might-not-need-an-effect
5.2 Defer State Reads to Usage Point
Impact: MEDIUM (avoids unnecessary subscriptions)
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
Incorrect: subscribes to all searchParams changes
Correct: reads on demand, no subscription
5.3 Do not wrap a simple expression with a primitive result type in useMemo
Impact: LOW-MEDIUM (wasted computation on every render)
When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in useMemo.
Calling useMemo and comparing hook dependencies may consume more resources than the expression itself.
Incorrect:
Correct:
5.4 Don't Define Components Inside Components
Impact: HIGH (prevents remount on every render)
Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
A common reason developers do this is to access parent variables without passing props. Always pass props instead.
Incorrect: remounts on every render
Every time UserProfile renders, Avatar and Stats are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
Correct: pass props instead
Symptoms of this bug:
- Input fields lose focus on every keystroke
- Animations restart unexpectedly
useEffectcleanup/setup runs on every parent render- Scroll position resets inside the component
5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant
Impact: MEDIUM (restores memoization by using a constant for default value)
When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in memo().
To address this issue, extract the default value into a constant.
Incorrect: onClick has different values on every rerender
Correct: stable default value
5.6 Extract to Memoized Components
Impact: MEDIUM (enables early returns)
Extract expensive work into memoized components to enable early returns before computation.
Incorrect: computes avatar even when loading
Correct: skips computation when loading
Note: If your project has React Compiler enabled, manual memoization with memo() and useMemo() is not necessary. The compiler automatically optimizes re-renders.
5.7 Narrow Effect Dependencies
Impact: LOW (minimizes effect re-runs)
Specify primitive dependencies instead of objects to minimize effect re-runs.
Incorrect: re-runs on any user field change
Correct: re-runs only when id changes
For derived state, compute outside effect:
5.8 Put Interaction Logic in Event Handlers
Impact: MEDIUM (avoids effect re-runs and duplicate side effects)
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
Incorrect: event modeled as state + effect
Correct: do it in the handler
Reference: https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler
5.9 Split Combined Hook Computations
Impact: MEDIUM (avoids recomputing independent steps)
When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
Incorrect: changing sortOrder recomputes filtering
Correct: filtering only recomputes when products or category change
This pattern also applies to useEffect when combining unrelated side effects:
Incorrect: both effects run when either dependency changes
Correct: effects run independently
Note: If your project has React Compiler enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
5.10 Subscribe to Derived State
Impact: MEDIUM (reduces re-render frequency)
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
Incorrect: re-renders on every pixel change
Correct: re-renders only when boolean changes
5.11 Use Functional setState Updates
Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
Incorrect: requires state as dependency
The first callback is recreated every time items changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial items value.
Correct: stable callbacks, no stale closures
Benefits:
- Stable callback references - Callbacks don't need to be recreated when state changes
- No stale closures - Always operates on the latest state value
- Fewer dependencies - Simplifies dependency arrays and reduces memory leaks
- Prevents bugs - Eliminates the most common source of React closure bugs
When to use functional updates:
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
When direct updates are fine:
- Setting state to a static value:
setCount(0) - Setting state from props/arguments only:
setName(newName) - State doesn't depend on previous value
Note: If your project has React Compiler enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
5.12 Use Lazy State Initialization
Impact: MEDIUM (wasted computation on every render)
Pass a function to useState for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
Incorrect: runs on every render
Correct: runs only once
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (useState(0)), direct references (useState(props.value)), or cheap literals (useState({})), the function form is unnecessary.
5.13 Use Transitions for Non-Urgent Updates
Impact: MEDIUM (maintains UI responsiveness)
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
Incorrect: blocks UI on every scroll
Correct: non-blocking updates
5.14 Use useDeferredValue for Expensive Derived Renders
Impact: MEDIUM (keeps input responsive during heavy computation)
When user input triggers expensive computations or renders, use useDeferredValue to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
Incorrect: input feels laggy while filtering
Correct: input stays snappy, results render when ready
When to use:
- Filtering/searching large lists
- Expensive visualizations (charts, graphs) reacting to input
- Any derived state that causes noticeable render delays
Note: Wrap the expensive computation in useMemo with the deferred value as a dependency, otherwise it still runs on every render.
Reference: https://react.dev/reference/react/useDeferredValue
5.15 Use useRef for Transient Values
Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in useRef instead of useState. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
Incorrect: renders every update
Correct: no re-render for tracking
6. Rendering Performance
Impact: MEDIUM
Optimizing the rendering process reduces the work the browser needs to do.
6.1 Animate SVG Wrapper Instead of SVG Element
Impact: LOW (enables hardware acceleration)
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a <div> and animate the wrapper instead.
Incorrect: animating SVG directly - no hardware acceleration
Correct: animating wrapper div - hardware accelerated
This applies to all CSS transforms and transitions (transform, opacity, translate, scale, rotate). The wrapper div allows browsers to use GPU acceleration for smoother animations.
6.2 CSS content-visibility for Long Lists
Impact: HIGH (faster initial render)
Apply content-visibility: auto to defer off-screen rendering.
CSS:
Example:
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
6.3 Hoist Static JSX Elements
Impact: LOW (avoids re-creation)
Extract static JSX outside components to avoid re-creation.
Incorrect: recreates element every render
Correct: reuses same element
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
Note: If your project has React Compiler enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
6.4 Optimize SVG Precision
Impact: LOW (reduces file size)
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
Incorrect: excessive precision
Correct: 1 decimal place
Automate with SVGO:
6.5 Prevent Hydration Mismatch Without Flickering
Impact: MEDIUM (avoids visual flicker and hydration errors)
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
Incorrect: breaks SSR
Server-side rendering will fail because localStorage is undefined.
Incorrect: visual flickering
Component first renders with default value (light), then updates after hydration, causing a visible flash of incorrect content.
Correct: no flicker, no hydration mismatch
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
6.6 Suppress Expected Hydration Mismatches
Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these expected mismatches, wrap the dynamic text in an element with suppressHydrationWarning to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
Incorrect: known mismatch warnings
Correct: suppress expected mismatch only
6.7 Use Activity Component for Show/Hide
Impact: MEDIUM (preserves state/DOM)
Use React's <Activity> to preserve state/DOM for expensive components that frequently toggle visibility.
Usage:
Avoids expensive re-renders and state loss.
6.8 Use defer or async on Script Tags
Impact: HIGH (eliminates render-blocking)
Script tags without defer or async block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
defer: Downloads in parallel, executes after HTML parsing completes, maintains execution orderasync: Downloads in parallel, executes immediately when ready, no guaranteed order
Use defer for scripts that depend on DOM or other scripts. Use async for independent scripts like analytics.
Incorrect: blocks rendering
Correct: non-blocking
Note: In Next.js, prefer the next/script component with strategy prop instead of raw script tags:
Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer
6.9 Use Explicit Conditional Rendering
Impact: LOW (prevents rendering 0 or NaN)
Use explicit ternary operators (? :) instead of && for conditional rendering when the condition can be 0, NaN, or other falsy values that render.
Incorrect: renders "0" when count is 0
Correct: renders nothing when count is 0
6.10 Use React DOM Resource Hints
Impact: HIGH (reduces load time for critical resources)
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
prefetchDNS(href): Resolve DNS for a domain you expect to connect topreconnect(href): Establish connection (DNS + TCP + TLS) to a serverpreload(href, options): Fetch a resource (stylesheet, font, script, image) you'll use soonpreloadModule(href): Fetch an ES module you'll use soonpreinit(href, options): Fetch and evaluate a stylesheet or scriptpreinitModule(href): Fetch and evaluate an ES module
Example: preconnect to third-party APIs
Example: preload critical fonts and styles
Example: preload modules for code-split routes
When to use each:
| API | Use case |
|-----|----------|
| prefetchDNS | Third-party domains you'll connect to later |
| preconnect | APIs or CDNs you'll fetch from immediately |
| preload | Critical resources needed for current page |
| preloadModule | JS modules for likely next navigation |
| preinit | Stylesheets/scripts that must execute early |
| preinitModule | ES modules that must execute early |
Reference: https://react.dev/reference/react-dom#resource-preloading-apis
6.11 Use useTransition Over Manual Loading States
Impact: LOW (reduces re-renders and improves code clarity)
Use useTransition instead of manual useState for loading states. This provides built-in isPending state and automatically manages transitions.
Incorrect: manual loading state
Correct: useTransition with built-in pending state
Benefits:
- Automatic pending state: No need to manually manage
setIsLoading(true/false) - Error resilience: Pending state correctly resets even if the transition throws
- Better responsiveness: Keeps the UI responsive during updates
- Interrupt handling: New transitions automatically cancel pending ones
Reference: https://react.dev/reference/react/useTransition
7. JavaScript Performance
Impact: LOW-MEDIUM
Micro-optimizations for hot paths can add up to meaningful improvements.
7.1 Avoid Layout Thrashing
Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)
Avoid interleaving style writes with layout reads. When you read a layout property (like offsetWidth, getBoundingClientRect(), or getComputedStyle()) between style changes, the browser is forced to trigger a synchronous reflow.
This is OK: browser batches style changes
Incorrect: interleaved reads and writes force reflows
Correct: batch writes, then read once
Correct: batch reads, then writes
Better: use CSS classes
React example:
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See this gist and CSS Triggers for more information on layout-forcing operations.
7.2 Build Index Maps for Repeated Lookups
Impact: LOW-MEDIUM (1M ops to 2K ops)
Multiple .find() calls by the same key should use a Map.
Incorrect (O(n) per lookup):
Correct (O(1) per lookup):
Build map once (O(n)), then all lookups are O(1).
For 1000 orders × 1000 users: 1M ops → 2K ops.
7.3 Cache Property Access in Loops
Impact: LOW-MEDIUM (reduces lookups)
Cache object property lookups in hot paths.
Incorrect: 3 lookups × N iterations
Correct: 1 lookup total
7.4 Cache Repeated Function Calls
Impact: MEDIUM (avoid redundant computation)
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
Incorrect: redundant computation
Correct: cached results
Simpler pattern for single-value functions:
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Reference: https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast
7.5 Cache Storage API Calls
Impact: LOW-MEDIUM (reduces expensive I/O)
localStorage, sessionStorage, and document.cookie are synchronous and expensive. Cache reads in memory.
Incorrect: reads storage on every call
Correct: Map cache
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
Cookie caching:
Important: invalidate on external changes
If storage can change externally (another tab, server-set cookies), invalidate cache:
7.6 Combine Multiple Array Iterations
Impact: LOW-MEDIUM (reduces iterations)
Multiple .filter() or .map() calls iterate the array multiple times. Combine into one loop.
Incorrect: 3 iterations
Correct: 1 iteration
7.7 Defer Non-Critical Work with requestIdleCallback
Impact: MEDIUM (keeps UI responsive during background tasks)
Use requestIdleCallback() to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
Incorrect: blocks main thread during user interaction
Correct: defers non-critical work to idle time
With timeout for required work:
Chunking large tasks:
With fallback for unsupported browsers:
When to use:
- Analytics and telemetry
- Saving state to localStorage/IndexedDB
- Prefetching resources for likely next actions
- Processing non-urgent data transformations
- Lazy initialization of non-critical features
When NOT to use:
- User-initiated actions that need immediate feedback
- Rendering updates the user is waiting for
- Time-sensitive operations
7.8 Early Length Check for Array Comparisons
Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
Incorrect: always runs expensive comparison
Two O(n log n) sorts run even when current.length is 5 and original.length is 100. There is also overhead of joining the arrays and comparing the strings.
Correct (O(1) length check first):
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
- It avoids mutating the original arrays
- It returns early when a difference is found
7.9 Early Return from Functions
Impact: LOW-MEDIUM (avoids unnecessary computation)
Return early when result is determined to skip unnecessary processing.
Incorrect: processes all items even after finding answer
Correct: returns immediately on first error
7.10 Hoist RegExp Creation
Impact: LOW-MEDIUM (avoids recreation)
Don't create RegExp inside render. Hoist to module scope or memoize with useMemo().
Incorrect: new RegExp every render
Correct: memoize or hoist
Warning: global regex has mutable state
Global regex (/g) has mutable lastIndex state:
7.11 Use flatMap to Map and Filter in One Pass
Impact: LOW-MEDIUM (eliminates intermediate array)
Chaining .map().filter(Boolean) creates an intermediate array and iterates twice. Use .flatMap() to transform and filter in a single pass.
Incorrect: 2 iterations, intermediate array
Correct: 1 iteration, no intermediate array
More examples:
When to use:
- Transforming items while filtering some out
- Conditional mapping where some inputs produce no output
- Parsing/validating where invalid inputs should be skipped
7.12 Use Loop for Min/Max Instead of Sort
Impact: LOW (O(n) instead of O(n log n))
Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
Incorrect (O(n log n) - sort to find latest):
Sorts the entire array just to find the maximum value.
Incorrect (O(n log n) - sort for oldest and newest):
Still sorts unnecessarily when only min/max are needed.
Correct (O(n) - single loop):
Single pass through the array, no copying, no sorting.
Alternative: Math.min/Math.max for small arrays
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see the fiddle. Use the loop approach for reliability.
7.13 Use Set/Map for O(1) Lookups
Impact: LOW-MEDIUM (O(n) to O(1))
Convert arrays to Set/Map for repeated membership checks.
Incorrect (O(n) per check):
Correct (O(1) per check):
7.14 Use toSorted() Instead of sort() for Immutability
Impact: MEDIUM-HIGH (prevents mutation bugs in React state)
.sort() mutates the array in place, which can cause bugs with React state and props. Use .toSorted() to create a new sorted array without mutation.
Incorrect: mutates original array
Correct: creates new array
Why this matters in React:
- Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
- Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
Browser support: fallback for older browsers
.toSorted() is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
Other immutable array methods:
.toSorted()- immutable sort.toReversed()- immutable reverse.toSpliced()- immutable splice.with()- immutable element replacement
8. Advanced Patterns
Impact: LOW
Advanced patterns for specific cases that require careful implementation.
8.1 Do Not Put Effect Events in Dependency Arrays
Impact: LOW (avoids unnecessary effect re-runs and lint errors)
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by useEffectEvent in a useEffect dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
Incorrect: Effect Event added as a dependency
Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
Correct: depend on reactive values, not the Effect Event
Reference: https://react.dev/reference/react/useEffectEvent#effect-event-in-deps
8.2 Initialize App Once, Not Per Mount
Impact: LOW-MEDIUM (avoids duplicate init in development)
Do not put app-wide initialization that must run once per app load inside useEffect([]) of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
Incorrect: runs twice in dev, re-runs on remount
Correct: once per app load
Reference: https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application
8.3 Store Event Handlers in Refs
Impact: LOW (stable subscriptions)
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
Incorrect: re-subscribes on every render
Correct: stable subscription
Alternative: use useEffectEvent if you're on latest React:
useEffectEvent provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
8.4 useEffectEvent for Stable Callback Refs
Impact: LOW (prevents effect re-runs)
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
Incorrect: effect re-runs on every callback change
Correct: using React's useEffectEvent