git:20261002.e962f2b to git:20261002.427fecc
7 added, 1 removed, first 3,000 lines shown. Audit B to B.
# React Best Practices
<!-- Generated by scripts/compile-react-guidance.ts. Edit rules/ or metadata.json instead. -->
**Version 1.0.0**
Vercel Engineering
January 2026
Use [SKILL.md](SKILL.md) and only the rules relevant to the task. This compiled reference is for deliberate full-guide reading. Apply optimizations only for a supported performance mechanism; ratings and example gains are not measurements of the current application.
Repository-maintained React and Next.js guidance adapted from Vercel's rules. Select rules by a concrete performance mechanism and workload. Dependencies and caches are conditional options, and impact ratings prioritize investigation rather than establish application performance gains.
## Contents
1. **Eliminating Waterfalls**
- 1.1 [Check Cheap Conditions Before Async Flags](#async-cheap-condition-before-await)
- 1.2 [Defer Await Until Needed](#async-defer-await)
- 1.3 [Dependency-Based Parallelization](#async-dependencies)
- 1.4 [Prevent Waterfall Chains in API Routes](#async-api-routes)
- 1.5 [Promise.all() for Independent Operations](#async-parallel)
- 1.6 [Strategic Suspense Boundaries](#async-suspense-boundaries)
2. **Bundle Size Optimization**
- 2.1 [Avoid Barrel File Imports](#bundle-barrel-imports)
- 2.2 [Conditional Module Loading](#bundle-conditional)
- 2.3 [Defer Non-Critical Third-Party Libraries](#bundle-defer-third-party)
- 2.4 [Dynamic Imports for Heavy Components](#bundle-dynamic-imports)
- 2.5 [Prefer Statically Analyzable Paths](#bundle-analyzable-paths)
- 2.6 [Preload Based on User Intent](#bundle-preload)
3. **Server-Side Performance**
- 3.1 [Authenticate Server Actions Like API Routes](#server-auth-actions)
- 3.2 [Avoid Duplicate Serialization in RSC Props](#server-dedup-props)
- 3.3 [Avoid Shared Module State for Request Data](#server-no-shared-module-state)
- 3.4 [Cross-Request LRU Caching](#server-cache-lru)
- 3.5 [Hoist Static I/O to Module Level](#server-hoist-static-io)
- 3.6 [Minimize Serialization at RSC Boundaries](#server-serialization)
- 3.7 [Parallel Data Fetching with Component Composition](#server-parallel-fetching)
- 3.8 [Parallel Nested Data Fetching](#server-parallel-nested-fetching)
- 3.9 [Per-Request Deduplication with React.cache()](#server-cache-react)
- 3.10 [Use after() for Non-Blocking Operations](#server-after-nonblocking)
4. **Client-Side Data Fetching**
- 4.1 [Deduplicate Global Event Listeners](#client-event-listeners)
- 4.2 [Use Passive Event Listeners for Scrolling Performance](#client-passive-event-listeners)
- 4.3 [Use SWR for Automatic Deduplication](#client-swr-dedup)
- 4.4 [Version and Minimize localStorage Data](#client-localstorage-schema)
5. **Re-render Optimization**
- 5.1 [Calculate Derived State During Rendering](#rerender-derived-state-no-effect)
- 5.2 [Defer State Reads to Usage Point](#rerender-defer-reads)
- 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#rerender-simple-expression-in-memo)
- 5.4 [Don't Define Components Inside Components](#rerender-no-inline-components)
- 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#rerender-memo-with-default-value)
- 5.6 [Extract to Memoized Components](#rerender-memo)
- 5.7 [Narrow Effect Dependencies](#rerender-dependencies)
- 5.8 [Put Interaction Logic in Event Handlers](#rerender-move-effect-to-event)
- 5.9 [Split Combined Hook Computations](#rerender-split-combined-hooks)
- 5.10 [Subscribe to Derived State](#rerender-derived-state)
- 5.11 [Use Functional setState Updates](#rerender-functional-setstate)
- 5.12 [Use Lazy State Initialization](#rerender-lazy-state-init)
- 5.13 [Use Transitions for Non-Urgent Updates](#rerender-transitions)
- 5.14 [Use useDeferredValue for Expensive Derived Renders](#rerender-use-deferred-value)
- 5.15 [Use useRef for Transient Values](#rerender-use-ref-transient-values)
6. **Rendering Performance**
- 6.1 [Animate SVG Wrapper Instead of SVG Element](#rendering-animate-svg-wrapper)
- 6.2 [CSS content-visibility for Long Lists](#rendering-content-visibility)
- 6.3 [Hoist Static JSX Elements](#rendering-hoist-jsx)
- 6.4 [Optimize SVG Precision](#rendering-svg-precision)
- 6.5 [Prevent Hydration Mismatch Without Flickering](#rendering-hydration-no-flicker)
- 6.6 [Suppress Expected Hydration Mismatches](#rendering-hydration-suppress-warning)
- 6.7 [Use Activity Component for Show/Hide](#rendering-activity)
- 6.8 [Use Explicit Conditional Rendering](#rendering-conditional-render)
- 6.9 [Use React DOM Resource Hints](#rendering-resource-hints)
- 6.10 [Use defer or async on Script Tags](#rendering-script-defer-async)
- 6.11 [Use useTransition Over Manual Loading States](#rendering-usetransition-loading)
7. **JavaScript Performance**
- 7.1 [Avoid Layout Thrashing](#js-batch-dom-css)
- 7.2 [Build Index Maps for Repeated Lookups](#js-index-maps)
- 7.3 [Cache Property Access in Loops](#js-cache-property-access)
- 7.4 [Cache Repeated Function Calls](#js-cache-function-results)
- 7.5 [Cache Storage API Calls](#js-cache-storage)
- 7.6 [Combine Multiple Array Iterations](#js-combine-iterations)
- 7.7 [Defer Non-Critical Work with requestIdleCallback](#js-request-idle-callback)
- 7.8 [Early Length Check for Array Comparisons](#js-length-check-first)
- 7.9 [Early Return from Functions](#js-early-exit)
- 7.10 [Hoist RegExp Creation](#js-hoist-regexp)
- 7.11 [Use Loop for Min/Max Instead of Sort](#js-min-max-loop)
- 7.12 [Use Set/Map for O(1) Lookups](#js-set-map-lookups)
- 7.13 [Use flatMap to Map and Filter in One Pass](#js-flatmap-filter)
- 7.14 [Use toSorted() Instead of sort() for Immutability](#js-tosorted-immutable)
8. **Advanced Patterns**
- 8.1 [Do Not Put Effect Events in Dependency Arrays](#advanced-effect-event-deps)
- 8.2 [Initialize App Once, Not Per Mount](#advanced-init-once)
- 8.3 [Store Event Handlers in Refs](#advanced-event-handler-refs)
- 8.4 [useEffectEvent for Stable Callback Refs](#advanced-use-latest)
## 1. Eliminating Waterfalls
**Investigation priority: CRITICAL**
Remove sequential waits on the critical path when the operations are genuinely independent. The benefit depends on their durations and required ordering.
---
<a id="async-cheap-condition-before-await"></a>
### 1.1 Check Cheap Conditions Before Async Flags
[Source rule](rules/async-cheap-condition-before-await.md)
**Investigation priority: 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](rules/async-defer-await.md) for `flag && cheapCondition` style checks.
**Incorrect:**
```typescript
const someFlag = await getFlag()
if (someFlag && someCondition) {
// ...
}
```
**Correct:**
```typescript
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.
---
<a id="async-defer-await"></a>
### 1.2 Defer Await Until Needed
[Source rule](rules/async-defer-await.md)
**Investigation priority: 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):**
```typescript
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):**
```typescript
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):**
```typescript
// Incorrect: always fetches the resource, even for callers who may not edit
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
const resource = await getResource(resourceId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
if (!resource) {
return { error: 'Not found' }
}
return await updateResourceData(resource, permissions)
}
// Correct: fetches the resource only once the caller is allowed to edit
async function updateResource(resourceId: string, userId: string) {
const permissions = await fetchPermissions(userId)
if (!permissions.canEdit) {
return { error: 'Forbidden' }
}
const resource = await getResource(resourceId)
if (!resource) {
return { error: 'Not found' }
}
return await updateResourceData(resource, permissions)
}
```
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive. Never defer an authorization check behind a lookup whose result reveals whether the resource exists; the permission check stays first.
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](rules/async-cheap-condition-before-await.md).
---
<a id="async-dependencies"></a>
### 1.3 Dependency-Based Parallelization
[Source rule](rules/async-dependencies.md)
**Investigation priority: CRITICAL (avoids waiting on unrelated dependencies; gains depend on task durations)**
Use this pattern when an operation waits for work it does not depend on and that wait matters on the actual path. Express the dependency graph with existing scheduling facilities or ordinary promises first. Preserve required sequencing, error handling, and cancellation behavior.
**Incorrect (profile waits for config unnecessarily):**
```typescript
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
```
**Direct dependency scheduling:**
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
**Optional library for a sufficiently complex graph:**
Consider `better-all` when it is already used by the project or its dependency scheduling materially simplifies the demonstrated workload. Do not add it for a small graph that is already clear with promises.
```typescript
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](https://github.com/shuding/better-all)
---
<a id="async-api-routes"></a>
### 1.4 Prevent Waterfall Chains in API Routes
[Source rule](rules/async-api-routes.md)
**Investigation priority: CRITICAL (overlaps independent work when sequencing is unnecessary)**
When a route's critical path contains avoidable sequential waits, start genuinely independent operations together. Do not move authorized work before its authorization check, or change ordering, failure, or resource-use semantics merely to overlap requests.
**Incorrect (config waits for auth, data waits for both):**
```typescript
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):**
```typescript
export async function GET(request: Request) {
const sessionPromise = auth()
const configPromise = fetchConfig()
// Both promises get a handler in the same tick they are created. Awaiting
// `sessionPromise` on its own first would leave `configPromise` unobserved;
// a fast config failure would then be an unhandled rejection.
const [config, data] = await Promise.all([
configPromise,
sessionPromise.then(session => fetchData(session.user.id))
])
return Response.json({ data, config })
}
```
Attach a handler to every promise you start before the first `await`, by passing it to `Promise.all` or chaining `.then` immediately. A promise left unobserved across an `await` becomes an unhandled rejection if it fails first, which crashes a Node process by default.
For more complex dependency chains, compare existing scheduling facilities and direct promise composition before considering `better-all`. See [Dependency-Based Parallelization](rules/async-dependencies.md) for the conditions that justify it.
---
<a id="async-parallel"></a>
### 1.5 Promise.all() for Independent Operations
[Source rule](rules/async-parallel.md)
**Investigation priority: CRITICAL (removes sequential round trips)**
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
**Incorrect (sequential execution, 3 round trips):**
```typescript
const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()
```
**Correct (parallel execution, 1 round trip):**
```typescript
const [user, posts, comments] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchComments()
])
```
---
<a id="async-suspense-boundaries"></a>
### 1.6 Strategic Suspense Boundaries
[Source rule](rules/async-suspense-boundaries.md)
**Investigation priority: 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):**
```tsx
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):**
```tsx
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):**
```tsx
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
**Investigation priority: CRITICAL**
Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
---
<a id="bundle-barrel-imports"></a>
### 2.1 Avoid Barrel File Imports
[Source rule](rules/bundle-barrel-imports.md)
**Investigation priority: 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):**
```tsx
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):**
```js
// next.config.js - automatically optimizes barrel imports at build time
module.exports = {
experimental: {
optimizePackageImports: ['lucide-react', '@mui/material']
}
}
```
```tsx
// 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):**
```tsx
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: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
---
<a id="bundle-conditional"></a>
### 2.2 Conditional Module Loading
[Source rule](rules/bundle-conditional.md)
**Investigation priority: HIGH (loads large data only when needed)**
Load large data or modules only when a feature is activated.
**Example (lazy-load animation frames):**
```tsx
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.
---
<a id="bundle-defer-third-party"></a>
### 2.3 Defer Non-Critical Third-Party Libraries
[Source rule](rules/bundle-defer-third-party.md)
**Investigation priority: MEDIUM (loads after hydration)**
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
**Incorrect (blocks initial bundle):**
```tsx
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
**Correct (loads after hydration):**
```tsx
// components/analytics.tsx
// `ssr: false` is only allowed in a Client Component, so the dynamic import lives here.
'use client'
import dynamic from 'next/dynamic'
export const Analytics = dynamic(
() => import('@vercel/analytics/react').then(m => m.Analytics),
{ ssr: false }
)
```
```tsx
// app/layout.tsx
import { Analytics } from '@/components/analytics'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}
```
---
<a id="bundle-dynamic-imports"></a>
### 2.4 Dynamic Imports for Heavy Components
[Source rule](rules/bundle-dynamic-imports.md)
**Investigation priority: CRITICAL (directly affects TTI and LCP)**
Use `next/dynamic` to lazy-load large components not needed on initial render.
**Incorrect (Monaco ships in the main chunk):**
```tsx
import { MonacoEditor } from './monaco-editor'
function CodePanel({ code }: { code: string }) {
return <MonacoEditor value={code} />
}
```
**Correct (Monaco loads on demand):**
```tsx
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} />
}
```
---
<a id="bundle-analyzable-paths"></a>
### 2.5 Prefer Statically Analyzable Paths
[Source rule](rules/bundle-analyzable-paths.md)
**Investigation priority: 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
#### Import Paths
**Incorrect (the bundler cannot tell what may be imported):**
```ts
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):**
```ts
const PAGE_MODULES = {
home: () => import('./pages/home'),
settings: () => import('./pages/settings'),
} as const
const Page = await PAGE_MODULES[pageName]()
```
#### File-System Paths
**Incorrect (a 2-value enum still hides the final path from static analysis):**
```ts
const baseDir = path.join(process.cwd(), 'content/' + contentKind)
```
**Correct (make each final path literal at the callsite):**
```ts
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: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
---
<a id="bundle-preload"></a>
### 2.6 Preload Based on User Intent
[Source rule](rules/bundle-preload.md)
**Investigation priority: MEDIUM (reduces perceived latency)**
Preload heavy bundles before they're needed to reduce perceived latency.
**Example (preload on hover/focus):**
```tsx
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>
)
}
```
**Example (preload when feature flag is enabled):**
```tsx
function FlagsProvider({ children, flags }: Props) {
useEffect(() => {
if (flags.editorEnabled && typeof window !== 'undefined') {
void import('./monaco-editor').then(mod => mod.init())
}
}, [flags.editorEnabled])
return <FlagsContext.Provider value={flags}>
{children}
</FlagsContext.Provider>
}
```
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
---
## 3. Server-Side Performance
**Investigation priority: HIGH**
Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
---
<a id="server-auth-actions"></a>
### 3.1 Authenticate Server Actions Like API Routes
[Source rule](rules/server-auth-actions.md)
**Investigation priority: 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):**
```typescript
'use server'
export async function deleteUser(userId: string) {
// Anyone can call this! No auth check
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**Correct (authentication inside the action):**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { unauthorized } from '@/lib/errors'
export async function deleteUser(userId: string) {
// Always check auth inside the action
const session = await verifySession()
if (!session) {
throw unauthorized('Must be logged in')
}
// Check authorization too
if (session.user.role !== 'admin' && session.user.id !== userId) {
throw unauthorized('Cannot delete other users')
}
await db.user.delete({ where: { id: userId } })
return { success: true }
}
```
**With input validation:**
```typescript
'use server'
import { verifySession } from '@/lib/auth'
import { z } from 'zod'
const updateProfileSchema = z.object({
userId: z.string().uuid(),
name: z.string().min(1).max(100),
email: z.string().email()
})
export async function updateProfile(data: unknown) {
// Authenticate first, so unauthenticated callers learn nothing about the schema
const session = await verifySession()
if (!session) {
throw new Error('Unauthorized')
}
// Then validate input
const validated = updateProfileSchema.parse(data)
// Then authorize
if (session.user.id !== validated.userId) {
throw new Error('Can only update own profile')
}
// Finally perform the mutation
await db.user.update({
where: { id: validated.userId },
data: {
name: validated.name,
email: validated.email
}
})
return { success: true }
}
```
Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
---
<a id="server-dedup-props"></a>
### 3.2 Avoid Duplicate Serialization in RSC Props
[Source rule](rules/server-dedup-props.md)
**Investigation priority: 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):**
```tsx
// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
```
**Correct (sends 3 strings):**
```tsx
// RSC: send once
<ClientList usernames={usernames} />
// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])
```
**Nested deduplication behavior:**
Deduplication works recursively. Impact varies by data type:
- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
```tsx
// string[] - duplicates everything
usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
// object[] - duplicates array structure only
users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
```
**Operations breaking deduplication (create new references):**
- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
**More examples:**
```tsx
// ❌ Bad
<C users={users} active={users.filter(u => u.active)} />
<C product={product} productName={product.name} />
// ✅ Good
<C users={users} />
<C product={product} />
// Do filtering/destructuring in client
```
**Exception:** Pass derived data when transformation is expensive or client doesn't need original.
---
<a id="server-no-shared-module-state"></a>
### 3.3 Avoid Shared Module State for Request Data
[Source rule](rules/server-no-shared-module-state.md)
**Investigation priority: 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):**
```tsx
let currentUser: User | null = null
export default async function Page() {
currentUser = await auth()
return <Dashboard />
}
async function Dashboard() {
return <div>{currentUser?.name}</div>
}
```
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):**
```tsx
export default async function Page() {
const user = await auth()
return <Dashboard user={user} />
}
function Dashboard({ user }: { user: User | null }) {
return <div>{user?.name}</div>
}
```
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](rules/server-hoist-static-io.md).
---
<a id="server-cache-lru"></a>
### 3.4 Cross-Request LRU Caching
[Source rule](rules/server-cache-lru.md)
**Investigation priority: HIGH (reuses costly reads when freshness and isolation permit)**
Consider a bounded cross-request cache only when repeated reads have meaningful cost and the data may be reused under an explicit freshness and isolation policy. Reuse an existing cache first. Define key identity, lifetime, size bounds, and invalidation ownership before adding an LRU dependency; ordinary sequential requests alone do not justify it.
An LRU cache can help when a bounded working set recurs and evicting entries is acceptable. Choose limits from the workload and memory budget. TTL and invalidation must match the data contract; do not copy example limits as application requirements.
Cache public data only when it has the same meaning for every caller. Include tenant, locale, version, or other relevant identity when results differ. Do not share authorization-dependent data or accept stale results when the contract requires fresh state. Choose a narrower scope or no cache when those guarantees cannot be preserved.
Use precise cache value types and distinguish a cache miss from valid falsy values. Account for failed loads and concurrent fills when they affect correctness. The write path or another identified owner must invalidate entries when the freshness contract requires it.
A process-local cache is an optimization, not durable storage or a guarantee of reuse across replicas and restarts. Verify the deployment's process lifetime and measure hit rate, latency, and memory cost. A shared cache service needs its own demonstrated requirement; do not add one automatically when local reuse is limited.
Reference: [lru-cache documentation](https://isaacs.github.io/node-lru-cache/)
---
<a id="server-hoist-static-io"></a>
### 3.5 Hoist Static I/O to Module Level
[Source rule](rules/server-hoist-static-io.md)
**Investigation priority: 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):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
export async function GET(request: Request) {
// Runs on EVERY request - expensive!
const fontData = await fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = await fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Correct (loads once at module initialization):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
// Module-level: runs ONCE when module is first imported
const fontData = fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
export async function GET(request: Request) {
// Await the already-started promises
const [font, logo] = await Promise.all([fontData, logoData])
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logo} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: font }] }
)
}
```
**Correct (synchronous fs at module level):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
import { readFileSync } from 'fs'
import { join } from 'path'
// Synchronous read at module level - blocks only during module init
const fontData = readFileSync(
join(process.cwd(), 'public/fonts/Inter.ttf')
)
const logoData = readFileSync(
join(process.cwd(), 'public/images/logo.png')
)
export async function GET(request: Request) {
return new ImageResponse(
<div style={{ fontFamily: 'Inter' }}>
<img src={logoData} />
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Incorrect (reads config on every call):**
```typescript
import fs from 'node:fs/promises'
export async function processRequest(data: Data) {
const config = JSON.parse(
await fs.readFile('./config.json', 'utf-8')
)
const template = await fs.readFile('./template.html', 'utf-8')
return render(template, data, config)
}
```
**Correct (hoists config and template to module level):**
```typescript
import fs from 'node:fs/promises'
const configPromise = fs
.readFile('./config.json', 'utf-8')
.then(JSON.parse)
const templatePromise = fs.readFile('./template.html', 'utf-8')
export async function processRequest(data: Data) {
const [config, template] = await Promise.all([
configPromise,
templatePromise,
])
return render(template, data, config)
}
```
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](https://vercel.com/docs/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.
---
<a id="server-serialization"></a>
### 3.6 Minimize Serialization at RSC Boundaries
[Source rule](rules/server-serialization.md)
**Investigation priority: 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):**
```tsx
async function Page() {
const user = await fetchUser() // 50 fields
return <Profile user={user} />
}
'use client'
function Profile({ user }: { user: User }) {
return <div>{user.name}</div> // uses 1 field
}
```
**Correct (serializes only 1 field):**
```tsx
async function Page() {
const user = await fetchUser()
return <Profile name={user.name} />
}
'use client'
function Profile({ name }: { name: string }) {
return <div>{name}</div>
}
```
---
<a id="server-parallel-fetching"></a>
### 3.7 Parallel Data Fetching with Component Composition
[Source rule](rules/server-parallel-fetching.md)
**Investigation priority: 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):**
```tsx
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):**
```tsx
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:**
```tsx
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>
)
}
```
---
<a id="server-parallel-nested-fetching"></a>
### 3.8 Parallel Nested Data Fetching
[Source rule](rules/server-parallel-nested-fetching.md)
**Investigation priority: 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):**
```tsx
const chats = await Promise.all(
chatIds.map(id => getChat(id))
)
const chatAuthors = await Promise.all(
chats.map(chat => getUser(chat.author))
)
```
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):**
```tsx
const chatAuthors = await Promise.all(
chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
)
```
Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
---
<a id="server-cache-react"></a>
### 3.9 Per-Request Deduplication with React.cache()
[Source rule](rules/server-cache-react.md)
**Investigation priority: MEDIUM (deduplicates within request)**
Consider `React.cache()` when the same costly computation or read repeats during a React Server Component render and sharing its result within that request preserves behavior. Reuse existing deduplication first. It is not a general-purpose server cache or a reason to cache every authentication check or database query.
**Usage:**
```typescript
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 }
})
})
```
During a supported server render, calls to the same memoized function can share the result. React invalidates this cache between server requests, and errors are cached too. Verify that those semantics fit the operation.
**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):**
```typescript
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):**
```typescript
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:
```typescript
const params = { uid: 1 }
getUser(params) // Query runs
getUser(params) // Cache hit (same reference)
```
**Next.js-Specific Note:**
Check the installed Next.js version and execution context for existing request memoization before adding another layer. Consider `React.cache()` for repeated non-fetch work only when its request scope and result/error reuse fit the requirement. A single call or an already-deduplicated operation gains nothing merely from another wrapper.
Reference: [React.cache documentation](https://react.dev/reference/react/cache)
---
<a id="server-after-nonblocking"></a>
### 3.10 Use after() for Non-Blocking Operations
[Source rule](rules/server-after-nonblocking.md)
**Investigation priority: 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):**
```tsx
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Logging blocks the response
const userAgent = request.headers.get('user-agent') || 'unknown'
await logUserAction({ userAgent })
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
**Correct (non-blocking):**
```tsx
import { after } from 'next/server'
import { headers, cookies } from 'next/headers'
import { logUserAction } from '@/app/utils'
export async function POST(request: Request) {
// Perform mutation
await updateDatabase(request)
// Log after response is sent
after(async () => {
const userAgent = (await headers()).get('user-agent') || 'unknown'
const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
// Await the work so `after()` keeps the function alive until logging finishes
await logUserAction({ sessionCookie, userAgent })
})
return new Response(JSON.stringify({ status: 'success' }), {
status: 200,
headers: { 'Content-Type': 'application/json' }
})
}
```
The response is sent immediately while logging happens in the background. Return or await every promise inside the callback: `after()` waits for the callback's promise, so a dropped promise can be cut off when the function instance ends.
**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](https://nextjs.org/docs/app/api-reference/functions/after)
---
## 4. Client-Side Data Fetching
**Investigation priority: MEDIUM-HIGH**
Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
---
<a id="client-event-listeners"></a>
### 4.1 Deduplicate Global Event Listeners
[Source rule](rules/client-event-listeners.md)
**Investigation priority: LOW (single listener for N components)**
Consider sharing listeners when repeated subscriptions create meaningful dispatch or lifecycle cost. Reuse an existing event owner or subscription facility first. `useSWRSubscription()` is an option in a project already using SWR; do not add SWR solely to replace a few inexpensive listeners. Preserve callback identity, cleanup, and event semantics.
**Incorrect (N instances = N listeners):**
```tsx
function useKeyboardShortcut(key: string, callback: () => void) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && e.key === key) {
callback()
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
}, [key, callback])
}
```
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
**Correct (N instances = 1 listener):**
```tsx
import useSWRSubscription from 'swr/subscription'
// Module-level Map to track callbacks per key
const keyCallbacks = new Map<string, Set<() => void>>()
function useKeyboardShortcut(key: string, callback: () => void) {
// Register this callback in the Map
useEffect(() => {
if (!keyCallbacks.has(key)) {
keyCallbacks.set(key, new Set())
}
keyCallbacks.get(key)!.add(callback)
return () => {
const set = keyCallbacks.get(key)
if (set) {
set.delete(callback)
if (set.size === 0) {
keyCallbacks.delete(key)
}
}
}
}, [key, callback])
useSWRSubscription('global-keydown', () => {
const handler = (e: KeyboardEvent) => {
if (e.metaKey && keyCallbacks.has(e.key)) {
keyCallbacks.get(e.key)!.forEach(cb => cb())
}
}
window.addEventListener('keydown', handler)
return () => window.removeEventListener('keydown', handler)
})
}
function Profile() {
// Multiple shortcuts will share the same listener
useKeyboardShortcut('p', () => { /* ... */ })
useKeyboardShortcut('k', () => { /* ... */ })
// ...
}
```
---
<a id="client-passive-event-listeners"></a>
### 4.2 Use Passive Event Listeners for Scrolling Performance
[Source rule](rules/client-passive-event-listeners.md)
**Investigation priority: 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:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch)
document.addEventListener('wheel', handleWheel)
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**Correct:**
```typescript
useEffect(() => {
const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
document.addEventListener('touchstart', handleTouch, { passive: true })
document.addEventListener('wheel', handleWheel, { passive: true })
return () => {
document.removeEventListener('touchstart', handleTouch)
document.removeEventListener('wheel', handleWheel)
}
}, [])
```
**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()`.
---
<a id="client-swr-dedup"></a>
### 4.3 Use SWR for Automatic Deduplication
[Source rule](rules/client-swr-dedup.md)
**Investigation priority: MEDIUM-HIGH (automatic deduplication)**
Apply request deduplication when several consumers make equivalent requests and the redundant work matters. Reuse the project's existing data layer first. SWR is one option when already adopted or when its caching and revalidation model meets a demonstrated need; this rule does not require installing or migrating to it.
Check request identity, cache scope, user-dependent data, and mutation freshness before sharing results. A one-off request without meaningful duplication does not justify a new data-fetching layer.
**Potential repeated work when many instances mount:**
```tsx
function UserList() {
const [users, setUsers] = useState([])
useEffect(() => {
fetch('/api/users')
.then(r => r.json())
.then(setUsers)
}, [])
}
```
**SWR option when it fits the project:**
```tsx
import useSWR from 'swr'
function UserList() {
const { data: users } = useSWR('/api/users', fetcher)
}
```
**For immutable data:**
```tsx
import useSWRImmutable from 'swr/immutable'
function StaticContent() {
const { data } = useSWRImmutable('/api/config', fetcher)
}
```
**For mutations:**
```tsx
import useSWRMutation from 'swr/mutation'
function UpdateButton() {
const { trigger } = useSWRMutation('/api/user', updateUser)
return <button onClick={() => trigger()}>Update</button>
}
```
Reference: [https://swr.vercel.app](https://swr.vercel.app)
---
<a id="client-localstorage-schema"></a>
### 4.4 Version and Minimize localStorage Data
[Source rule](rules/client-localstorage-schema.md)
**Investigation priority: 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:**
```typescript
// No version, stores everything, no error handling
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
const data = localStorage.getItem('userConfig')
```
**Correct:**
```typescript
const VERSION = 'v2'
function saveConfig(config: { theme: string; language: string }): boolean {
try {
localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
return true
} catch {
// Throws in incognito/private browsing, quota exceeded, or disabled
return false
}
}
function loadConfig() {
try {
const data = localStorage.getItem(`userConfig:${VERSION}`)
return data ? JSON.parse(data) : null
} catch {
return null
}
}
// Migration from v1 to v2
function migrate() {
try {
const v1 = localStorage.getItem('userConfig:v1')
if (v1) {
const old = JSON.parse(v1)
const saved = saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
// Remove the old version only once the new one is stored, or a failed write loses both
if (saved) localStorage.removeItem('userConfig:v1')
}
} catch {}
}
```
**Store minimal fields from server responses:**
```typescript
// User object has 20+ fields, only store what UI needs
function cachePrefs(user: FullUser) {
try {
localStorage.setItem('prefs:v1', JSON.stringify({
theme: user.preferences.theme,
notifications: user.preferences.notifications
}))
} catch {}
}
```
**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
**Investigation priority: MEDIUM**
Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
---
<a id="rerender-derived-state-no-effect"></a>
### 5.1 Calculate Derived State During Rendering
[Source rule](rules/rerender-derived-state-no-effect.md)
**Investigation priority: 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):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const [fullName, setFullName] = useState('')
useEffect(() => {
setFullName(firstName + ' ' + lastName)
}, [firstName, lastName])
return <p>{fullName}</p>
}
```
**Correct (derive during render):**
```tsx
function Form() {
const [firstName, setFirstName] = useState('First')
const [lastName, setLastName] = useState('Last')
const fullName = firstName + ' ' + lastName
return <p>{fullName}</p>
}
```
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
---
<a id="rerender-defer-reads"></a>
### 5.2 Defer State Reads to Usage Point
[Source rule](rules/rerender-defer-reads.md)
**Investigation priority: 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):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const searchParams = useSearchParams()
const handleShare = () => {
const ref = searchParams.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
**Correct (reads on demand, no subscription):**
```tsx
function ShareButton({ chatId }: { chatId: string }) {
const handleShare = () => {
const params = new URLSearchParams(window.location.search)
const ref = params.get('ref')
shareChat(chatId, { ref })
}
return <button onClick={handleShare}>Share</button>
}
```
---
<a id="rerender-simple-expression-in-memo"></a>
### 5.3 Do not wrap a simple expression with a primitive result type in useMemo
[Source rule](rules/rerender-simple-expression-in-memo.md)
**Investigation priority: 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:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = useMemo(() => {
return user.isLoading || notifications.isLoading
}, [user.isLoading, notifications.isLoading])
if (isLoading) return <Skeleton />
// return some markup
}
```
**Correct:**
```tsx
function Header({ user, notifications }: Props) {
const isLoading = user.isLoading || notifications.isLoading
if (isLoading) return <Skeleton />
// return some markup
}
```
---
<a id="rerender-no-inline-components"></a>
### 5.4 Don't Define Components Inside Components
[Source rule](rules/rerender-no-inline-components.md)
**Investigation priority: 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):**
```tsx
function UserProfile({ user, theme }) {
// Defined inside to access `theme` - BAD
const Avatar = () => (
<img
src={user.avatarUrl}
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
/>
)
// Defined inside to access `user` - BAD
const Stats = () => (
<div>
<span>{user.followers} followers</span>
<span>{user.posts} posts</span>
</div>
)
return (
<div>
<Avatar />
<Stats />
</div>
)
}
```
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):**
```tsx
function Avatar({ src, theme }: { src: string; theme: string }) {
return (
<img
src={src}
className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
/>
)
}
function Stats({ followers, posts }: { followers: number; posts: number }) {
return (
<div>
<span>{followers} followers</span>
<span>{posts} posts</span>
</div>
)
}
function UserProfile({ user, theme }) {
return (
<div>
<Avatar src={user.avatarUrl} theme={theme} />
<Stats followers={user.followers} posts={user.posts} />
</div>
)
}
```
**Symptoms of this bug:**
- Input fields lose focus on every keystroke
- Animations restart unexpectedly
- `useEffect` cleanup/setup runs on every parent render
- Scroll position resets inside the component
---
<a id="rerender-memo-with-default-value"></a>
### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant
[Source rule](rules/rerender-memo-with-default-value.md)
**Investigation priority: MEDIUM (restores memoization by using a constant for default value)**
A default value for a non-primitive optional parameter, such as an array, function, or object, is re-created on every render of the component. `memo()` itself is unaffected, because defaults are applied after props are compared, but any memoized child, `useMemo`, `useCallback`, or effect that receives the default sees a new identity each render and re-runs.
To address this issue, extract the default value into a constant.
**Incorrect (`onClick` is a new function on every render of `UserAvatar`):**
```tsx
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
**Correct (stable default value):**
```tsx
const NOOP = () => {};
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
// ...
})
// Used without optional onClick
<UserAvatar />
```
---
<a id="rerender-memo"></a>
### 5.6 Extract to Memoized Components
[Source rule](rules/rerender-memo.md)
**Investigation priority: MEDIUM (enables early returns)**
Extract expensive work into memoized components to enable early returns before computation.
**Incorrect (computes avatar even when loading):**
```tsx
function Profile({ user, loading }: Props) {
const avatar = useMemo(() => {
const id = computeAvatarId(user)
return <Avatar id={id} />
}, [user])
if (loading) return <Skeleton />
return <div>{avatar}</div>
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatar id={id} />
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton />
return (
<div>
<UserAvatar user={user} />
</div>
)
}
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
---
<a id="rerender-dependencies"></a>
### 5.7 Narrow Effect Dependencies
[Source rule](rules/rerender-dependencies.md)
**Investigation priority: LOW (minimizes effect re-runs)**
Specify primitive dependencies instead of objects to minimize effect re-runs.
**Incorrect (re-runs on any user field change):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user])
```
**Correct (re-runs only when id changes):**
```tsx
useEffect(() => {
console.log(user.id)
}, [user.id])
```
**For derived state, compute outside effect:**
```tsx
// Incorrect: runs on width=767, 766, 765...
useEffect(() => {
if (width < 768) {
enableMobileMode()
}
}, [width])
// Correct: runs only on boolean transition
const isMobile = width < 768
useEffect(() => {
if (isMobile) {
enableMobileMode()
}
}, [isMobile])
```
---
<a id="rerender-move-effect-to-event"></a>
### 5.8 Put Interaction Logic in Event Handlers
[Source rule](rules/rerender-move-effect-to-event.md)
**Investigation priority: 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):**
```tsx
function Form() {
const [submitted, setSubmitted] = useState(false)
const theme = useContext(ThemeContext)
useEffect(() => {
if (submitted) {
post('/api/register')
showToast('Registered', theme)
}
}, [submitted, theme])
return <button onClick={() => setSubmitted(true)}>Submit</button>
}
```
**Correct (do it in the handler):**
```tsx
function Form() {
const theme = useContext(ThemeContext)
function handleSubmit() {
post('/api/register')
showToast('Registered', theme)
}
return <button onClick={handleSubmit}>Submit</button>
}
```
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
---
<a id="rerender-split-combined-hooks"></a>
### 5.9 Split Combined Hook Computations
[Source rule](rules/rerender-split-combined-hooks.md)
**Investigation priority: 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):**
```tsx
const sortedProducts = useMemo(() => {
const filtered = products.filter((p) => p.category === category)
const sorted = filtered.toSorted((a, b) =>
sortOrder === "asc" ? a.price - b.price : b.price - a.price
)
return sorted
}, [products, category, sortOrder])
```
**Correct (filtering only recomputes when products or category change):**
```tsx
const filteredProducts = useMemo(
() => products.filter((p) => p.category === category),
[products, category]
)
const sortedProducts = useMemo(
() =>
filteredProducts.toSorted((a, b) =>
sortOrder === "asc" ? a.price - b.price : b.price - a.price
),
[filteredProducts, sortOrder]
)
```
This pattern also applies to `useEffect` when combining unrelated side effects:
**Incorrect (both effects run when either dependency changes):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
document.title = `${pageTitle} | My App`
}, [pathname, pageTitle])
```
**Correct (effects run independently):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
}, [pathname])
useEffect(() => {
document.title = `${pageTitle} | My App`
}, [pageTitle])
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
---
<a id="rerender-derived-state"></a>
### 5.10 Subscribe to Derived State
[Source rule](rules/rerender-derived-state.md)
**Investigation priority: 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):**
```tsx
function Sidebar() {
const width = useWindowWidth() // updates continuously
const isMobile = width < 768
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
**Correct (re-renders only when boolean changes):**
```tsx
function Sidebar() {
const isMobile = useMediaQuery('(max-width: 767px)')
return <nav className={isMobile ? 'mobile' : 'desktop'} />
}
```
---
<a id="rerender-functional-setstate"></a>
### 5.11 Use Functional setState Updates
[Source rule](rules/rerender-functional-setstate.md)
**Investigation priority: 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):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
const addItems = useCallback((newItems: Item[]) => {
setItems([...items, ...newItems])
}, [items]) // ❌ items dependency causes recreations
// Risk of stale closure if dependency is forgotten
const removeItem = useCallback((id: string) => {
setItems(items.filter(item => item.id !== id))
}, []) // ❌ Missing items dependency - will use stale items!
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
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):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Stable callback, never recreated
const addItems = useCallback((newItems: Item[]) => {
setItems(curr => [...curr, ...newItems])
}, []) // ✅ No dependencies needed
// Always uses latest state, no stale closure risk
const removeItem = useCallback((id: string) => {
setItems(curr => curr.filter(item => item.id !== id))
}, []) // ✅ Safe and stable
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
}
```
**Benefits:**
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
2. **No stale closures** - Always operates on the latest state value
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
4. **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](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
---
<a id="rerender-lazy-state-init"></a>
### 5.12 Use Lazy State Initialization
[Source rule](rules/rerender-lazy-state-init.md)
**Investigation priority: 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):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
const [query, setQuery] = useState('')
// When query changes, buildSearchIndex runs again unnecessarily
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs on every render
const [settings, setSettings] = useState(
JSON.parse(localStorage.getItem('settings') || '{}')
)
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
**Correct (runs only once):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs ONLY on initial render
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
const [query, setQuery] = useState('')
return <SearchResults index={searchIndex} query={query} />
}
function UserProfile() {
// JSON.parse runs only on initial render
const [settings, setSettings] = useState(() => {
const stored = localStorage.getItem('settings')
return stored ? JSON.parse(stored) : {}
})
return <SettingsForm settings={settings} onChange={setSettings} />
}
```
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations. A `useState` initializer still runs during server rendering, so read browser storage this way only in client-only components; for pages that render on the server, see [Prevent Hydration Mismatch Flicker](rules/rendering-hydration-no-flicker.md).
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
---
<a id="rerender-transitions"></a>
### 5.13 Use Transitions for Non-Urgent Updates
[Source rule](rules/rerender-transitions.md)
**Investigation priority: MEDIUM (maintains UI responsiveness)**
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
**Incorrect (blocks UI on every scroll):**
```tsx
function ScrollTracker() {
const [scrollY, setScrollY] = useState(0)
useEffect(() => {
const handler = () => setScrollY(window.scrollY)
window.addEventListener('scroll', handler, { passive: true })
return () => window.removeEventListener('scroll', handler)
}, [])
}
```
**Correct (non-blocking updates):**
```tsx
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)
}, [])
}
```
---
<a id="rerender-use-deferred-value"></a>
### 5.14 Use useDeferredValue for Expensive Derived Renders
[Source rule](rules/rerender-use-deferred-value.md)
**Investigation priority: 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):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState('')
const filtered = items.filter(item => fuzzyMatch(item, query))
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<ResultsList results={filtered} />
</>
)
}
```
**Correct (input stays snappy, results render when ready):**
```tsx
function Search({ items }: { items: Item[] }) {
const [query, setQuery] = useState('')
const deferredQuery = useDeferredValue(query)
const filtered = useMemo(
() => items.filter(item => fuzzyMatch(item, deferredQuery)),
[items, deferredQuery]
)
const isStale = query !== deferredQuery
return (
<>
<input value={query} onChange={e => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.7 : 1 }}>
<ResultsList results={filtered} />
</div>
</>
)
}
+
+ // The deferred render only skips work if the child bails out when its props
+ // are unchanged, so the list must be memoized.
+ const ResultsList = memo(function ResultsList({ results }: { results: Item[] }) {
+ // ...
+ })
```
**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.
+ **Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render. Memoize the component that renders the result as well: during the urgent render, `deferredQuery` and `filtered` are unchanged, and only a `memo` child skips re-rendering with unchanged props. Without that, the expensive child still renders on every keystroke.
Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)
---
<a id="rerender-use-ref-transient-values"></a>
### 5.15 Use useRef for Transient Values
[Source rule](rules/rerender-use-ref-transient-values.md)
**Investigation priority: 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):**
```tsx
function Tracker() {
const [lastX, setLastX] = useState(0)
useEffect(() => {
const onMove = (e: MouseEvent) => setLastX(e.clientX)
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
style={{
position: 'fixed',
top: 0,
left: lastX,
width: 8,
height: 8,
background: 'black',
}}
/>
)
}
```
**Correct (no re-render for tracking):**
```tsx
function Tracker() {
const lastXRef = useRef(0)
const dotRef = useRef<HTMLDivElement>(null)
useEffect(() => {
const onMove = (e: MouseEvent) => {
lastXRef.current = e.clientX
const node = dotRef.current
if (node) {
node.style.transform = `translateX(${e.clientX}px)`
}
}
window.addEventListener('mousemove', onMove)
return () => window.removeEventListener('mousemove', onMove)
}, [])
return (
<div
ref={dotRef}
style={{
position: 'fixed',
top: 0,
left: 0,
width: 8,
height: 8,
background: 'black',
transform: 'translateX(0px)',
}}
/>
)
}
```
---
## 6. Rendering Performance
**Investigation priority: MEDIUM**
Optimizing the rendering process reduces the work the browser needs to do.
---
<a id="rendering-animate-svg-wrapper"></a>
### 6.1 Animate SVG Wrapper Instead of SVG Element
[Source rule](rules/rendering-animate-svg-wrapper.md)
**Investigation priority: 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):**
```tsx
function LoadingSpinner() {
return (
<svg
className="animate-spin"
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
)
}
```
**Correct (animating wrapper div - hardware accelerated):**
```tsx
function LoadingSpinner() {
return (
<div className="animate-spin">
<svg
width="24"
height="24"
viewBox="0 0 24 24"
>
<circle cx="12" cy="12" r="10" stroke="currentColor" />
</svg>
</div>
)
}
```
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.
---
<a id="rendering-content-visibility"></a>
### 6.2 CSS content-visibility for Long Lists
[Source rule](rules/rendering-content-visibility.md)
**Investigation priority: HIGH (faster initial render)**
Apply `content-visibility: auto` to defer off-screen rendering.
**CSS:**
```css
.message-item {
content-visibility: auto;
contain-intrinsic-size: 0 80px;
}
```
**Example:**
```tsx
function MessageList({ messages }: { messages: Message[] }) {
return (
<div className="overflow-y-auto h-screen">
{messages.map(msg => (
<div key={msg.id} className="message-item">
<Avatar user={msg.author} />
<div>{msg.content}</div>
</div>
))}
</div>
)
}
```
For 1000 messages, the browser skips layout and paint for the roughly 990 off-screen items until they scroll into view.
---
<a id="rendering-hoist-jsx"></a>
### 6.3 Hoist Static JSX Elements
[Source rule](rules/rendering-hoist-jsx.md)
**Investigation priority: LOW (avoids re-creation)**
Extract static JSX outside components to avoid re-creation.
**Incorrect (recreates element every render):**
```tsx
function LoadingSkeleton() {
return <div className="animate-pulse h-20 bg-gray-200" />
}
function Container() {
return (
<div>
{loading && <LoadingSkeleton />}
</div>
)
}
```
**Correct (reuses same element):**
```tsx
const loadingSkeleton = (
<div className="animate-pulse h-20 bg-gray-200" />
)
function Container() {
return (
<div>
{loading && loadingSkeleton}
</div>
)
}
```
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](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
---
<a id="rendering-svg-precision"></a>
### 6.4 Optimize SVG Precision
[Source rule](rules/rendering-svg-precision.md)
**Investigation priority: 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):**
```svg
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
```
**Correct (1 decimal place):**
```svg
<path d="M 10.3 20.8 L 30.9 40.2" />
```
**Automate with SVGO:**
```bash
npx svgo --precision=1 --multipass icon.svg
```
---
<a id="rendering-hydration-no-flicker"></a>
### 6.5 Prevent Hydration Mismatch Without Flickering
[Source rule](rules/rendering-hydration-no-flicker.md)
**Investigation priority: 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):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
const theme = localStorage.getItem('theme') || 'light'
return (
<div className={theme}>
{children}
</div>
)
}
```
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<div className={theme}>
{children}
</div>
)
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<div id="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
```
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.
---
<a id="rendering-hydration-suppress-warning"></a>
### 6.6 Suppress Expected Hydration Mismatches
[Source rule](rules/rendering-hydration-suppress-warning.md)
**Investigation priority: 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):**
```tsx
function Timestamp() {
return <span>{new Date().toLocaleString()}</span>
}
```
**Correct (suppress expected mismatch only):**
```tsx
function Timestamp() {
return (
<span suppressHydrationWarning>
{new Date().toLocaleString()}
</span>
)
}
```
---
<a id="rendering-activity"></a>
### 6.7 Use Activity Component for Show/Hide
[Source rule](rules/rendering-activity.md)
**Investigation priority: MEDIUM (preserves state/DOM)**
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
**Usage:**
```tsx
import { Activity } from 'react'
function Dropdown({ isOpen }: Props) {
return (
<Activity mode={isOpen ? 'visible' : 'hidden'}>
<ExpensiveMenu />
</Activity>
)
}
```
Avoids expensive re-renders and state loss.
---
<a id="rendering-conditional-render"></a>
### 6.8 Use Explicit Conditional Rendering
[Source rule](rules/rendering-conditional-render.md)
**Investigation priority: 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):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count && <span className="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
**Correct (renders nothing when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count > 0 ? <span className="badge">{count}</span> : null}
</div>
)
}
// When count = 0, renders: <div></div>
// When count = 5, renders: <div><span class="badge">5</span></div>
```
---
<a id="rendering-resource-hints"></a>
### 6.9 Use React DOM Resource Hints
[Source rule](rules/rendering-resource-hints.md)
**Investigation priority: 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 to
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
- **`preinitModule(href)`**: Fetch and evaluate an ES module
**Example (preconnect to third-party APIs):**
```tsx
import { preconnect, prefetchDNS } from 'react-dom'
export default function App() {
prefetchDNS('https://analytics.example.com')
preconnect('https://api.example.com')
return <main>{/* content */}</main>
}
```
**Example (preload critical fonts and styles):**
```tsx
import { preload, preinit } from 'react-dom'
export default function RootLayout({ children }) {
// Preload font file
preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
// Fetch and apply critical stylesheet immediately
preinit('/styles/critical.css', { as: 'style' })
return (
<html>
<body>{children}</body>
</html>
)
}
```
**Example (preload modules for code-split routes):**
```tsx
import { preloadModule, preinitModule } from 'react-dom'
function Navigation() {
const preloadDashboard = () => {
preloadModule('/dashboard.js', { as: 'script' })
}
return (
<nav>
<a href="/dashboard" onMouseEnter={preloadDashboard}>
Dashboard
</a>
</nav>
)
}
```
**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: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
---
<a id="rendering-script-defer-async"></a>
### 6.10 Use defer or async on Script Tags
[Source rule](rules/rendering-script-defer-async.md)
**Investigation priority: 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.