agentleFS
FranRomFranRom/pupila/.agents/skills/react-best-practices/AGENTS.md

pupila / react-best-practices

AGENTS.md36 starsChanged 7 months agoMITView on GitHub

Version 1.0.0 Vercel Engineering January 2026 Note: Document for agents + LLMs maintaining, generating, or refactoring React/Next.js codebases. Humans may find useful — guidance optimized for AI-assisted automation + consistency. Comprehensive perf optimization guide for React + Next.js, designed for agents/LLMs. 40+ rules across 8 categories, prioritized by impact from critical (kill waterfalls, cut bundle) to incremental (advanced patterns). Each rule: detailed explanation, real-world incorrect vs correct examples, impact metrics for automated refactoring + code generation.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

35 rules. About 0 are common, 19 are distinctive, and 16 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈19

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 16

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Keep original order if someCondition expensive, depends on flag, or side effects must run in fixed order.

    line 138
  2. Very specific:

    Create promises first, Promise.all() at end.

    line 261
  3. Distinctive:

    Instead of awaiting data in async components before returning JSX, use Suspense boundaries → wrapper UI shows faster while data loads.

    line 327
  4. Very specific:

    Import directly from source files.

    line 430
  5. Very specific:

    Use next/dynamic to lazy-load big components not needed at initial render.

    line 549
  6. Very specific:

    Use explicit maps or literal paths so reachable file set stays narrow + predictable.

    line 582
  7. Distinctive:

    Treat module scope on server as process-wide shared memory, NOT request-local state.

    line 841
  8. Distinctive:

    Use when sequential user actions hit multiple endpoints needing same data within seconds.

    line 910
  9. Distinctive:

    When NOT to use:

    line 1050
  10. Distinctive:

    Must pass objects → use same reference:

    line 1250
  11. Very specific:

    Use React.cache() to dedup these across component tree.

    line 1262
  12. Very specific:

    Use useSWRSubscription() to share global event listeners across instances.

    line 1347
  13. Very specific:

    Add { passive: true } to touch/wheel listeners → immediate scrolling.

    line 1417
  14. Distinctive:

    Add version prefix to keys, store only needed fields.

    line 1513
  15. Distinctive:

    Don't subscribe to dynamic state (searchParams, localStorage) if only read inside callbacks.

    line 1624
  16. Very specific:

    Every UserProfile render → Avatar + Stats are new types.

    line 1724
  17. Distinctive:

    Use primitive deps instead of objects — minimizes effect re-runs.

    line 1840
  18. Distinctive:

    Stable callback refs: - no recreate on state change

    line 2053
  19. Distinctive:

    No stale closures: - always operates on latest state

    line 2054
  20. Distinctive:

    No dep on previous value

    line 2069
  21. Distinctive:

    Use lazy init for: localStorage/sessionStorage reads, data structure builds (indexes, maps), DOM reads, heavy transforms.

    line 2123
  22. Very specific:

    Use defer for scripts depending on DOM or other scripts.

    line 2573
  23. Very specific:

    Use ternary (? :) instead of && when condition can be 0, NaN, or other falsy values that render.

    line 2614
  24. Very specific:

    Use useTransition instead of manual useState for loading.

    line 2729
  25. Very specific:

    Auto pending state: no manual setIsLoading(true/false)

    line 2789
  26. Very specific:

    Don't interleave style writes with layout reads.

    line 2808
  27. Distinctive:

    Prefer CSS classes over inline styles.

    line 2888
  28. Distinctive:

    Use module-level Map to cache function results when same function called repeatedly with same inputs during render.

    line 2954
  29. Distinctive:

    Use Map (not hook) — works everywhere: utilities, event handlers, not just components.

    line 3022
  30. Distinctive:

    If storage can change externally (another tab, server-set cookies), invalidate:

    line 3090
  31. Distinctive:

    No sort/join overhead when lengths differ

    line 3260
  32. Distinctive:

    No memory for joined strings (matters for big arrays)

    line 3261
  33. Distinctive:

    No mutation of originals

    line 3262
  34. Very specific:

    Don't create RegExp inside render.

    line 3315
  35. Very specific:

    Don't put app-wide once-per-load init inside useEffect([]).

    line 3622

≈ “Common” is an estimate: at least 1 in 5 of the 16,597 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

React Best Practices

Version 1.0.0 Vercel Engineering January 2026

Note: Document for agents + LLMs maintaining, generating, or refactoring React/Next.js codebases. Humans may find useful — guidance optimized for AI-assisted automation + consistency.


Abstract

Comprehensive perf optimization guide for React + Next.js, designed for agents/LLMs. 40+ rules across 8 categories, prioritized by impact from critical (kill waterfalls, cut bundle) to incremental (advanced patterns). Each rule: detailed explanation, real-world incorrect vs correct examples, impact metrics for automated refactoring + code generation.


Table of Contents

  1. Eliminating Waterfalls — CRITICAL
    • 1.1 Check Cheap Conditions Before Async Flags
    • 1.2 Defer Await Until Needed
    • 1.3 Dependency-Based Parallelization
    • 1.4 Prevent Waterfall Chains in API Routes
    • 1.5 Promise.all() for Independent Operations
    • 1.6 Strategic Suspense Boundaries
  2. Bundle Size Optimization — CRITICAL
    • 2.1 Avoid Barrel File Imports
    • 2.2 Conditional Module Loading
    • 2.3 Defer Non-Critical Third-Party Libraries
    • 2.4 Dynamic Imports for Heavy Components
    • 2.5 Prefer Statically Analyzable Paths
    • 2.6 Preload Based on User Intent
  3. 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
  4. Client-Side Data Fetching — MEDIUM-HIGH
    • 4.1 Deduplicate Global Event Listeners
    • 4.2 Use Passive Event Listeners for Scrolling Performance
    • 4.3 Use SWR for Automatic Deduplication
    • 4.4 Version and Minimize localStorage Data
  5. 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
  6. 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
  7. 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
  8. Advanced Patterns — LOW
    • 8.1 Do Not Put Effect Events in Dependency Arrays
    • 8.2 Initialize App Once, Not Per Mount
    • 8.3 Store Event Handlers in Refs
    • 8.4 useEffectEvent for Stable Callback Refs

1. Eliminating Waterfalls

Impact: CRITICAL

Waterfalls = #1 perf killer. Each sequential await adds full network latency. Eliminating yields largest gains.

1.1 Check Cheap Conditions Before Async Flags

Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)

Branch uses await for flag/remote value AND needs cheap sync condition (local props, request metadata, loaded state) → eval cheap one first. Otherwise pay async call even when compound can't be true.

Specialization of Defer Await Until Needed for flag && cheapCondition checks.

Incorrect:

const someFlag = await getFlag()

if (someFlag && someCondition) {
  // ...
}

Correct:

if (someCondition) {
  const someFlag = await getFlag()
  if (someFlag) {
    // ...
  }
}

Matters when getFlag hits network, feature-flag service, React.cache / DB: skipping when someCondition false removes cold-path cost.

Keep original order if someCondition expensive, depends on flag, or side effects must run in fixed order.

1.2 Defer Await Until Needed

Impact: HIGH (avoids blocking unused code paths)

Move await into branches where it's used. Don't block paths that don't need it.

Incorrect: blocks both branches

async function handleRequest(userId: string, skipProcessing: boolean) {
  const userData = await fetchUserData(userId)
  
  if (skipProcessing) {
    // Returns immediately but still waited for userData
    return { skipped: true }
  }
  
  // Only this branch uses userData
  return processUserData(userData)
}

Correct: blocks only when needed

async function handleRequest(userId: string, skipProcessing: boolean) {
  if (skipProcessing) {
    // Returns immediately without waiting
    return { skipped: true }
  }
  
  // Fetch only when needed
  const userData = await fetchUserData(userId)
  return processUserData(userData)
}

Another example: early return optimization

// Incorrect: always fetches permissions
async function updateResource(resourceId: string, userId: string) {
  const permissions = await fetchPermissions(userId)
  const resource = await getResource(resourceId)
  
  if (!resource) {
    return { error: 'Not found' }
  }
  
  if (!permissions.canEdit) {
    return { error: 'Forbidden' }
  }
  
  return await updateResourceData(resource, permissions)
}

// Correct: fetches only when needed
async function updateResource(resourceId: string, userId: string) {
  const resource = await getResource(resourceId)
  
  if (!resource) {
    return { error: 'Not found' }
  }
  
  const permissions = await fetchPermissions(userId)
  
  if (!permissions.canEdit) {
    return { error: 'Forbidden' }
  }
  
  return await updateResourceData(resource, permissions)
}

Valuable when skipped branch hits often or deferred op is expensive.

For await getFlag() + cheap sync guard (flag && someCondition), see Check Cheap Conditions Before Async Flags.

1.3 Dependency-Based Parallelization

Impact: CRITICAL (2-10× improvement)

For ops with partial deps, use better-all to maximize parallelism. Auto-starts each task at earliest possible moment.

Incorrect: profile waits for config unnecessarily

const [user, config] = await Promise.all([
  fetchUser(),
  fetchConfig()
])
const profile = await fetchProfile(user.id)

Correct: config + profile run in parallel

import { all } from 'better-all'

const { user, config, profile } = await all({
  async user() { return fetchUser() },
  async config() { return fetchConfig() },
  async profile() {
    return fetchProfile((await this.$.user).id)
  }
})

Alt without extra deps:

const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))

const [user, config, profile] = await Promise.all([
  userPromise,
  fetchConfig(),
  profilePromise
])

Create promises first, Promise.all() at end.

Reference: https://github.com/shuding/better-all

1.4 Prevent Waterfall Chains in API Routes

Impact: CRITICAL (2-10× improvement)

API routes + Server Actions: start independent ops immediately, even before await.

Incorrect: config waits for auth, data waits for both

export async function GET(request: Request) {
  const session = await auth()
  const config = await fetchConfig()
  const data = await fetchData(session.user.id)
  return Response.json({ data, config })
}

Correct: auth + config start immediately

export async function GET(request: Request) {
  const sessionPromise = auth()
  const configPromise = fetchConfig()
  const session = await sessionPromise
  const [config, data] = await Promise.all([
    configPromise,
    fetchData(session.user.id)
  ])
  return Response.json({ data, config })
}

For complex dep chains, use better-all to auto-maximize parallelism (see Dependency-Based Parallelization).

1.5 Promise.all() for Independent Operations

Impact: CRITICAL (2-10× improvement)

Async ops with no interdeps run concurrently via Promise.all().

Incorrect: sequential, 3 round trips

const user = await fetchUser()
const posts = await fetchPosts()
const comments = await fetchComments()

Correct: parallel, 1 round trip

const [user, posts, comments] = await Promise.all([
  fetchUser(),
  fetchPosts(),
  fetchComments()
])

1.6 Strategic Suspense Boundaries

Impact: HIGH (faster initial paint)

Instead of awaiting data in async components before returning JSX, use Suspense boundaries → wrapper UI shows faster while data loads.

Incorrect: wrapper blocked by fetch

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>
  )
}

Whole layout waits for data, only middle needs it.

Correct: wrapper renders immediately, data streams in

function Page() {
  return (
    <div>
      <div>Sidebar</div>
      <div>Header</div>
      <div>
        <Suspense fallback={<Skeleton />}>
          <DataDisplay />
        </Suspense>
      </div>
      <div>Footer</div>
    </div>
  )
}

async function DataDisplay() {
  const data = await fetchData() // Only blocks this component
  return <div>{data.content}</div>
}

Sidebar, Header, Footer render now. Only DataDisplay waits.

Alt: share promise across components

function Page() {
  // Start fetch immediately, but don't await
  const dataPromise = fetchData()
  
  return (
    <div>
      <div>Sidebar</div>
      <div>Header</div>
      <Suspense fallback={<Skeleton />}>
        <DataDisplay dataPromise={dataPromise} />
        <DataSummary dataPromise={dataPromise} />
      </Suspense>
      <div>Footer</div>
    </div>
  )
}

function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
  const data = use(dataPromise) // Unwraps the promise
  return <div>{data.content}</div>
}

function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
  const data = use(dataPromise) // Reuses the same promise
  return <div>{data.summary}</div>
}

Both share same promise → one fetch. Layout renders now, both components wait together.

When NOT to use:

  • Critical data for layout decisions (positioning)
  • SEO-critical above-fold content
  • Small fast queries where Suspense overhead isn't worth it
  • Avoiding layout shift (loading → content jump)

Trade-off: faster initial paint vs potential layout shift. Pick per UX priority.


2. Bundle Size Optimization

Impact: CRITICAL

Cutting initial bundle size improves Time to Interactive + Largest Contentful Paint.

2.1 Avoid Barrel File Imports

Impact: CRITICAL (200-800ms import cost, slow builds)

Import directly from source files. Don't load thousands of unused modules via barrels. Barrel files = entry points re-exporting multiple modules (e.g., index.js does export * from './module').

Popular icon/component libs can have up to 10,000 re-exports in entry file. Many React packages take 200-800ms just to import — hits dev speed + prod cold starts.

Why tree-shaking can't help: Lib marked external (not bundled) → bundler can't optimize. Bundle it for tree-shaking → builds slow analyzing entire module graph.

Incorrect: imports entire lib

import { Check, X, Menu } from 'lucide-react'
// Loads 1,583 modules, takes ~2.8s extra in dev
// Runtime cost: 200-800ms on every cold start

import { Button, TextField } from '@mui/material'
// Loads 2,225 modules, takes ~4.2s extra in dev

Correct - Next.js 13.5+ (recommended):

// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from 'lucide-react'
// Full TypeScript support, no manual path wrangling

Recommended: preserves TS type safety + editor autocomplete, kills barrel cost.

Correct - Direct imports (non-Next.js):

import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use

TS warning: Some libs (notably lucide-react) don't ship .d.ts for deep import paths. Importing from lucide-react/dist/esm/icons/check resolves to implicit any → errors under strict or noImplicitAny. Prefer optimizePackageImports when available, or verify lib exports types for subpaths before direct imports.

These opts: 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, faster HMR.

Libs 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/modules only when feature activates.

Example: lazy-load animation frames

function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
  const [frames, setFrames] = useState<Frame[] | null>(null)

  useEffect(() => {
    if (enabled && !frames && typeof window !== 'undefined') {
      import('./animation-frames.js')
        .then(mod => setFrames(mod.frames))
        .catch(() => setEnabled(false))
    }
  }, [enabled, frames, setEnabled])

  if (!frames) return <Skeleton />
  return <Canvas frames={frames} />
}

typeof window !== 'undefined' prevents bundling this module for SSR — smaller server bundle, faster builds.

2.3 Defer Non-Critical Third-Party Libraries

Impact: MEDIUM (loads after hydration)

Analytics, logging, error tracking don't block user interaction. Load post-hydration.

Incorrect: blocks initial bundle

import { Analytics } from '@vercel/analytics/react'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  )
}

Correct: loads post-hydration

import dynamic from 'next/dynamic'

const Analytics = dynamic(
  () => import('@vercel/analytics/react').then(m => m.Analytics),
  { ssr: false }
)

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Analytics />
      </body>
    </html>
  )
}

2.4 Dynamic Imports for Heavy Components

Impact: CRITICAL (directly affects TTI and LCP)

Use next/dynamic to lazy-load big components not needed at initial render.

Incorrect: Monaco bundles with main chunk ~300KB

import { MonacoEditor } from './monaco-editor'

function CodePanel({ code }: { code: string }) {
  return <MonacoEditor value={code} />
}

Correct: Monaco loads on demand

import dynamic from 'next/dynamic'

const MonacoEditor = dynamic(
  () => import('./monaco-editor').then(m => m.MonacoEditor),
  { ssr: false }
)

function CodePanel({ code }: { code: string }) {
  return <MonacoEditor value={code} />
}

2.5 Prefer Statically Analyzable Paths

Impact: HIGH (avoids accidental broad bundles and file traces)

Build tools work best when import + FS paths are obvious at build time. Hide real path in a variable or compose too dynamically → tool either includes broad file set, warns it can't analyze, or widens file tracing to be safe.

Use explicit maps or literal paths so reachable file set stays narrow + predictable. Same rule for import() and reading files in server/build code.

Broad analysis costs:

  • Larger server bundles
  • Slower builds
  • Worse cold starts
  • More memory

Incorrect: bundler can't tell what may be imported

const PAGE_MODULES = {
  home: './pages/home',
  settings: './pages/settings',
} as const

const Page = await import(PAGE_MODULES[pageName])

Correct: explicit map of allowed modules

const PAGE_MODULES = {
  home: () => import('./pages/home'),
  settings: () => import('./pages/settings'),
} as const

const Page = await PAGE_MODULES[pageName]()

Incorrect: 2-value enum hides final path from static analysis

const baseDir = path.join(process.cwd(), 'content/' + contentKind)

Correct: each final path literal at callsite

const baseDir =
  kind === ContentKind.Blog
    ? path.join(process.cwd(), 'content/blog')
    : path.join(process.cwd(), 'content/docs')

Next.js server code: matters for output file tracing too. path.join(process.cwd(), someVar) can widen traced file set because Next.js statically analyzes import, require, fs.

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 needed → cut perceived latency.

Example: preload on hover/focus

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 enabled

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>
}

typeof window !== 'undefined' prevents bundling preloaded modules for SSR — smaller server bundle, faster builds.


3. Server-Side Performance

Impact: HIGH

Optimizing SSR + data fetching kills server-side waterfalls + cuts response times.

3.1 Authenticate Server Actions Like API Routes

Impact: CRITICAL (prevents unauthorized access to server mutations)

Server Actions ("use server") = public endpoints, like API routes. Always verify auth + authz inside each Server Action — don't rely solely on middleware, layout guards, or page-level checks. Server Actions can be invoked directly.

Next.js docs: "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 auth check

'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: auth inside action

'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:

'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) {
  // Validate input first
  const validated = updateProfileSchema.parse(data)
  
  // Then authenticate
  const session = await verifySession()
  if (!session) {
    throw new Error('Unauthorized')
  }
  
  // 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

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 transforms (.toSorted(), .filter(), .map()) in client, not server.

Incorrect: duplicates array

// RSC: sends 6 strings (2 arrays × 3 items)
<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />

Correct: sends 3 strings

// RSC: send once
<ClientList usernames={usernames} />

// Client: transform there
'use client'
const sorted = useMemo(() => [...usernames].sort(), [usernames])

Nested dedup behavior:

// 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)

Dedup works recursively. Impact varies by data type:

  • string[], number[], boolean[]: HIGH impact — array + all primitives fully duplicated
  • object[]: LOW impact — array duplicated, nested objects deduplicated by reference

Ops breaking dedup: create new refs

  • Arrays: .toSorted(), .filter(), .map(), .slice(), [...arr]
  • Objects: {...obj}, Object.assign(), structuredClone(), JSON.parse(JSON.stringify())

More examples:

// ❌ 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 transform 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 RSC + client components rendered during SSR, don't use mutable module-level vars for request-scoped data. Server renders run concurrently in same process. One render writes to shared module state, another reads → race conditions, cross-request contamination, security bugs (user A's data appears in user B's response).

Treat module scope on server as process-wide shared memory, NOT request-local state.

Incorrect: request data leaks across concurrent renders

let currentUser: User | null = null

export default async function Page() {
  currentUser = await auth()
  return <Dashboard />
}

async function Dashboard() {
  return <div>{currentUser?.name}</div>
}

Two overlapping requests: request A sets currentUser, request B overwrites before A finishes rendering Dashboard.

Correct: keep request data local to render tree

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 / config loaded once at module scope
  • Shared caches designed for cross-request reuse + keyed correctly
  • Process-wide singletons not storing request/user-specific mutable data

For static assets + config, see Hoist Static I/O to Module Level.

3.4 Cross-Request LRU Caching

Impact: HIGH (caches across requests)

React.cache() works only within one request. For data shared across sequential requests (user clicks A then B), use LRU cache.

Implementation:

import { LRUCache } from 'lru-cache'

const cache = new LRUCache<string, any>({
  max: 1000,
  ttl: 5 * 60 * 1000  // 5 minutes
})

export async function getUser(id: string) {
  const cached = cache.get(id)
  if (cached) return cached

  const user = await db.user.findUnique({ where: { id } })
  cache.set(id, user)
  return user
}

// Request 1: DB query, result cached
// Request 2: cache hit, no DB query

Use when sequential user actions hit multiple endpoints needing same data within seconds.

With Vercel's Fluid Compute: LRU caching extra effective — concurrent requests share same function instance + cache. Cache persists across requests without external storage like Redis.

Traditional serverless: each invocation isolated → 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)

Loading static assets (fonts, logos, images, config) in route handlers/server functions → hoist I/O to module level. Module-level code runs once at first import, not on every request. Kills redundant FS reads/network fetches.

Incorrect: reads font file every request

// 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 init

// 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

// 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 every call

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 + template to module level

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:

  • Loading fonts for OG image generation
  • Static logos, icons, watermarks
  • Reading config files that don't change at runtime
  • Email templates, other static templates
  • Any static asset same across requests

When NOT to use:

  • Assets that vary per request/user
  • Files that may change at runtime (use cache with TTL)
  • Large files that'd consume too much memory if kept loaded
  • Sensitive data that shouldn't persist in memory

With Vercel's Fluid Compute, module-level caching extra effective — concurrent requests share function instance. Static assets stay in memory across requests, no cold start penalty.

Traditional serverless: each cold start re-executes module-level code; warm invocations reuse loaded assets until instance recycled.

3.6 Minimize Serialization at RSC Boundaries

Impact: HIGH (reduces data transfer size)

React Server/Client boundary serializes all object props to strings → embeds in HTML response + RSC requests. Serialized data directly hits page weight + load time. Size matters a lot. Only pass fields client actually uses.

Incorrect: serializes all 50 fields

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

async function Page() {
  const user = await fetchUser()
  return <Profile name={user.name} />
}

'use client'
function Profile({ name }: { name: string }) {
  return <div>{name}</div>
}

3.7 Parallel Data Fetching with Component Composition

Impact: CRITICAL (eliminates server-side waterfalls)

RSC executes sequentially within a tree. Restructure with composition to parallelize fetching.

Incorrect: Sidebar waits for Page's fetch

export default async function Page() {
  const header = await fetchHeader()
  return (
    <div>
      <div>{header}</div>
      <Sidebar />
    </div>
  )
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

Correct: both fetch simultaneously

async function Header() {
  const data = await fetchHeader()
  return <div>{data}</div>
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

export default function Page() {
  return (
    <div>
      <Header />
      <Sidebar />
    </div>
  )
}

Alt with children prop:

async function Header() {
  const data = await fetchHeader()
  return <div>{data}</div>
}

async function Sidebar() {
  const items = await fetchSidebarItems()
  return <nav>{items.map(renderItem)}</nav>
}

function Layout({ children }: { children: ReactNode }) {
  return (
    <div>
      <Header />
      {children}
    </div>
  )
}

export default function Page() {
  return (
    <Layout>
      <Sidebar />
    </Layout>
  )
}

3.8 Parallel Nested Data Fetching

Impact: CRITICAL (eliminates server-side waterfalls)

Fetching nested data in parallel → chain dependent fetches within each item's promise. Slow item won't block rest.

Incorrect: one slow item blocks all nested fetches

const chats = await Promise.all(
  chatIds.map(id => getChat(id))
)

const chatAuthors = await Promise.all(
  chats.map(chat => getUser(chat.author))
)

One slow getChat(id) out of 100 → authors of other 99 chats can't start loading even though data ready.

Correct: each item chains own nested fetch

const chatAuthors = await Promise.all(
  chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
)

Each item independently chains getChat → getUser. Slow chat doesn't block author fetches for others.

3.9 Per-Request Deduplication with React.cache()

Impact: MEDIUM (deduplicates within request)

React.cache() for server-side request dedup. Auth + DB queries benefit most.

Usage:

import { cache } from 'react'

export const getCurrentUser = cache(async () => {
  const session = await auth()
  if (!session?.user?.id) return null
  return await db.user.findUnique({
    where: { id: session.user.id }
  })
})

Within single request, multiple getCurrentUser() calls run query once.

Avoid inline objects as args:

React.cache() uses shallow eq (Object.is) for cache hits. Inline objects = new refs each call → no cache hits.

Incorrect: always cache miss

const getUser = cache(async (params: { uid: number }) => {
  return await db.user.findUnique({ where: { id: params.uid } })
})

// Each call creates new object, never hits cache
getUser({ uid: 1 })
getUser({ uid: 1 })  // Cache miss, runs query again

Correct: cache hit

const params = { uid: 1 }
getUser(params)  // Query runs
getUser(params)  // Cache hit (same reference)

Must pass objects → use same reference:

Next.js-specific note:

Next.js auto-extends fetch with request memoization. Requests with same URL + options auto-dedup within single request → React.cache() not needed for fetch. But still essential for other async tasks:

  • DB queries (Prisma, Drizzle, etc.)
  • Heavy computations
  • Auth checks
  • FS ops
  • Any non-fetch async work

Use React.cache() to dedup these across component tree.

Reference: https://react.dev/reference/react/cache

3.10 Use after() for Non-Blocking Operations

Impact: MEDIUM (faster response times)

Next.js's after() schedules work post-response. Stops logging, analytics, side effects from blocking response.

Incorrect: blocks response

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

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'
    
    logUserAction({ sessionCookie, userAgent })
  })
  
  return new Response(JSON.stringify({ status: 'success' }), {
    status: 200,
    headers: { 'Content-Type': 'application/json' }
  })
}

Response sent immediately, logging runs in background.

Common use cases:

  • Analytics tracking
  • Audit logging
  • Send notifications
  • Cache invalidation
  • Cleanup tasks

Important:

  • after() runs even if response fails or redirects
  • Works in Server Actions, Route Handlers, Server Components

Reference: https://nextjs.org/docs/app/api-reference/functions/after


4. Client-Side Data Fetching

Impact: MEDIUM-HIGH

Auto dedup + efficient fetching cut redundant network requests.

4.1 Deduplicate Global Event Listeners

Impact: LOW (single listener for N components)

Use useSWRSubscription() to share global event listeners across instances.

Incorrect: N instances = N listeners

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])
}

Each use of useKeyboardShortcut registers a new listener.

Correct: N instances = 1 listener

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', () => { /* ... */ })
  // ...
}

4.2 Use Passive Event Listeners for Scrolling Performance

Impact: MEDIUM (eliminates scroll delay caused by event listeners)

Add { passive: true } to touch/wheel listeners → immediate scrolling. Browsers wait for listeners to finish to check preventDefault() → scroll delay.

Incorrect:

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:

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 not calling preventDefault().

Don't use passive when: custom swipe gestures, custom zoom, anything needing preventDefault().

4.3 Use SWR for Automatic Deduplication

Impact: MEDIUM-HIGH (automatic deduplication)

SWR = request dedup + caching + revalidation across instances.

Incorrect: no dedup, each instance fetches

function UserList() {
  const [users, setUsers] = useState([])
  useEffect(() => {
    fetch('/api/users')
      .then(r => r.json())
      .then(setUsers)
  }, [])
}

Correct: instances share one request

import useSWR from 'swr'

function UserList() {
  const { data: users } = useSWR('/api/users', fetcher)
}

Immutable data:

import { useImmutableSWR } from '@/lib/swr'

function StaticContent() {
  const { data } = useImmutableSWR('/api/config', fetcher)
}

Mutations:

import { useSWRMutation } from 'swr/mutation'

function UpdateButton() {
  const { trigger } = useSWRMutation('/api/user', updateUser)
  return <button onClick={() => trigger()}>Update</button>
}

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, store only needed fields. Prevents schema conflicts + accidental sensitive-data storage.

Incorrect:

// No version, stores everything, no error handling
localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
const data = localStorage.getItem('userConfig')

Correct:

const VERSION = 'v2'

function saveConfig(config: { theme: string; language: string }) {
  try {
    localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
  } catch {
    // Throws in incognito/private browsing, quota exceeded, or disabled
  }
}

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)
      saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
      localStorage.removeItem('userConfig:v1')
    }
  } catch {}
}

Store minimal fields from server responses:

// 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() / setItem() throw in incognito (Safari, Firefox), on quota exceeded, or when disabled.

Benefits: schema evolution via versioning, smaller storage, no token/PII/internal-flag leakage.


5. Re-render Optimization

Impact: MEDIUM

Cutting unnecessary re-renders saves computation + improves UI responsiveness.

5.1 Calculate Derived State During Rendering

Impact: MEDIUM (avoids redundant renders and state drift)

Value computable from current props/state → don't store in state or update in effect. Derive during render → no extra renders + state drift. Don't set state in effects solely in response to prop changes; prefer derived values or keyed resets.

Incorrect: redundant state + effect

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

function Form() {
  const [firstName, setFirstName] = useState('First')
  const [lastName, setLastName] = useState('Last')
  const fullName = firstName + ' ' + lastName

  return <p>{fullName}</p>
}

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 only read inside callbacks.

Incorrect: subscribes to all searchParams changes

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

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>
}

5.3 Do not wrap a simple expression with a primitive result type in useMemo

Impact: LOW-MEDIUM (wasted computation on every render)

Simple expression (few logical/arithmetical operators) + primitive result (boolean, number, string) → don't wrap in useMemo.

useMemo call + dep comparison can cost more than expression itself.

Incorrect:

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:

function Header({ user, notifications }: Props) {
  const isLoading = user.isLoading || notifications.isLoading

  if (isLoading) return <Skeleton />
  // return some markup
}

5.4 Don't Define Components Inside Components

Impact: HIGH (prevents remount on every render)

Component defined inside another → new component type every render. React sees different component each time → fully remounts, destroying state + DOM.

Common reason: accessing parent variables without props. Always pass props.

Incorrect: remounts every render

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 UserProfile render → Avatar + Stats are new types. React unmounts old, mounts new — loses internal state, reruns effects, recreates DOM.

Correct: pass props

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 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)

Memoized component with default for non-primitive optional param (array, function, object) → calling without that param breaks memoization. New value instances every rerender fail memo() strict-equality.

Fix: extract default into a constant.

Incorrect: onClick differs every rerender

const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
  // ...
})

// Used without optional onClick
<UserAvatar />

Correct: stable default

const NOOP = () => {};

const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
  // ...
})

// Used without optional onClick
<UserAvatar />

5.6 Extract to Memoized Components

Impact: MEDIUM (enables early returns)

Extract expensive work into memoized components → enables early returns before computation.

Incorrect: computes avatar even when loading

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

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: React Compiler enabled → manual memo()/useMemo() unnecessary. Compiler auto-optimizes re-renders.

5.7 Narrow Effect Dependencies

Impact: LOW (minimizes effect re-runs)

Use primitive deps instead of objects — minimizes effect re-runs.

Incorrect: re-runs on any user field change

useEffect(() => {
  console.log(user.id)
}, [user])

Correct: re-runs only when id changes

useEffect(() => {
  console.log(user.id)
}, [user.id])

For derived state, compute outside effect:

// 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])

5.8 Put Interaction Logic in Event Handlers

Impact: MEDIUM (avoids effect re-runs and duplicate side effects)

Side effect triggered by user action (submit, click, drag) → run in event handler. Don't model action as state + effect — effects re-run on unrelated changes + can duplicate.

Incorrect: event modeled as state + effect

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 handler

function Form() {
  const theme = useContext(ThemeContext)

  function handleSubmit() {
    post('/api/register')
    showToast('Registered', theme)
  }

  return <button onClick={handleSubmit}>Submit</button>
}

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)

Hook with multiple independent tasks + different deps → split into separate hooks. Combined hook reruns all tasks when any dep changes, even if some tasks don't use changed value.

Incorrect: changing sortOrder recomputes filtering

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: filter only recomputes when products/category change

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]
)

Same pattern for useEffect combining unrelated side effects:

Incorrect: both effects run when either dep changes

useEffect(() => {
  analytics.trackPageView(pathname)
  document.title = `${pageTitle} | My App`
}, [pathname, pageTitle])

Correct: effects run independently

useEffect(() => {
  analytics.trackPageView(pathname)
}, [pathname])

useEffect(() => {
  document.title = `${pageTitle} | My App`
}, [pageTitle])

Note: React Compiler auto-optimizes dep tracking, may handle some of these.

5.10 Subscribe to Derived State

Impact: MEDIUM (reduces re-render frequency)

Subscribe to derived boolean instead of continuous values → fewer re-renders.

Incorrect: re-renders on every pixel change

function Sidebar() {
  const width = useWindowWidth()  // updates continuously
  const isMobile = width < 768
  return <nav className={isMobile ? 'mobile' : 'desktop'} />
}

Correct: re-renders only when boolean changes

function Sidebar() {
  const isMobile = useMediaQuery('(max-width: 767px)')
  return <nav className={isMobile ? 'mobile' : 'desktop'} />
}

5.11 Use Functional setState Updates

Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)

Updating state based on current value → use functional update form, not direct reference. Prevents stale closures, kills unneeded deps, creates stable callback refs.

Incorrect: needs state as dep

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} />
}

First callback recreated every items change → child re-renders. Second has stale closure bug — always references initial items.

Correct: stable callbacks, no stale closures

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 refs - no recreate on state change
  2. No stale closures - always operates on latest state
  3. Fewer deps - simpler dep arrays, less memory leak risk
  4. Prevents bugs - eliminates most common React closure bugs

Use functional updates for:

  • Any setState depending on current state value
  • Inside useCallback/useMemo when state needed
  • Event handlers referencing state
  • Async ops updating state

Direct updates fine for:

  • Static value: setCount(0)
  • From props/args only: setName(newName)
  • No dep on previous value

Note: React Compiler can auto-optimize some cases, but functional updates still recommended for correctness + stale closure prevention.

5.12 Use Lazy State Initialization

Impact: MEDIUM (wasted computation on every render)

Pass function to useState for expensive initial values. Without function form, initializer runs on every render even though value used once.

Incorrect: runs on every render

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 once

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 init for: localStorage/sessionStorage reads, data structure builds (indexes, maps), DOM reads, heavy transforms.

For simple primitives (useState(0)), direct refs (useState(props.value)), cheap literals (useState({})) → function form unnecessary.

5.13 Use Transitions for Non-Urgent Updates

Impact: MEDIUM (maintains UI responsiveness)

Mark frequent non-urgent state updates as transitions → keeps UI responsive.

Incorrect: blocks UI on every scroll

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

import { startTransition } from 'react'

function ScrollTracker() {
  const [scrollY, setScrollY] = useState(0)
  useEffect(() => {
    const handler = () => {
      startTransition(() => setScrollY(window.scrollY))
    }
    window.addEventListener('scroll', handler, { passive: true })
    return () => window.removeEventListener('scroll', handler)
  }, [])
}

5.14 Use useDeferredValue for Expensive Derived Renders

Impact: MEDIUM (keeps input responsive during heavy computation)

User input triggers expensive computations/renders → useDeferredValue keeps input responsive. Deferred value lags behind → React prioritizes input update + renders expensive result when idle.

Incorrect: input feels laggy during filter

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

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>
    </>
  )
}

Use for:

  • Filter/search large lists
  • Expensive visualizations (charts, graphs) reacting to input
  • Any derived state causing noticeable render delays

Note: Wrap expensive computation in useMemo with deferred value as dep — otherwise 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)

Value changes frequently + don't want re-render every update (mouse trackers, intervals, transient flags) → useRef not useState. Component state for UI; refs for temp DOM-adjacent values. Ref update doesn't trigger re-render.

Incorrect: renders every update

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

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

Impact: MEDIUM

Optimizing rendering reduces browser work.

6.1 Animate SVG Wrapper Instead of SVG Element

Impact: LOW (enables hardware acceleration)

Many browsers lack hardware accel for CSS3 animations on SVG. Wrap SVG in <div>, animate wrapper.

Incorrect: animating SVG directly — no hardware accel

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

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>
  )
}

Applies to all CSS transforms + transitions (transform, opacity, translate, scale, rotate). Wrapper div = GPU accel = smoother animations.

6.2 CSS content-visibility for Long Lists

Impact: HIGH (faster initial render)

content-visibility: auto defers off-screen rendering.

CSS:

.message-item {
  content-visibility: auto;
  contain-intrinsic-size: 0 80px;
}

Example:

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>
  )
}

1000 messages → browser skips layout/paint for ~990 off-screen (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

function LoadingSkeleton() {
  return <div className="animate-pulse h-20 bg-gray-200" />
}

function Container() {
  return (
    <div>
      {loading && <LoadingSkeleton />}
    </div>
  )
}

Correct: reuses same element

const loadingSkeleton = (
  <div className="animate-pulse h-20 bg-gray-200" />
)

function Container() {
  return (
    <div>
      {loading && loadingSkeleton}
    </div>
  )
}

Especially helpful for large static SVG nodes (expensive to recreate every render).

Note: React Compiler auto-hoists static JSX + optimizes re-renders → manual hoisting unnecessary.

6.4 Optimize SVG Precision

Impact: LOW (reduces file size)

Cut SVG coordinate precision → smaller file size. Optimal precision depends on viewBox size — reducing usually worth considering.

Incorrect: excessive precision

<path d="M 10.293847 20.847362 L 30.938472 40.192837" />

Correct: 1 decimal

<path d="M 10.3 20.8 L 30.9 40.2" />

Automate with SVGO:

npx svgo --precision=1 --multipass icon.svg

6.5 Prevent Hydration Mismatch Without Flickering

Impact: MEDIUM (avoids visual flicker and hydration errors)

Content depends on client storage (localStorage, cookies) → avoid both SSR breakage + post-hydration flicker by injecting sync script that updates DOM before React hydrates.

Incorrect: breaks SSR

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>
  )
}

SSR fails — localStorage undefined.

Incorrect: visual flicker

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 renders with default (light), then updates after hydration → visible flash of wrong content.

Correct: no flicker, no hydration mismatch

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) {}
            })();
          `,
        }}
      />
    </>
  )
}

Inline script runs synchronously before element shows → DOM has correct value. No flicker, no mismatch.

Useful for theme toggles, user prefs, auth state, any client-only data that should render immediately without flashing defaults.

6.6 Suppress Expected Hydration Mismatches

Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)

SSR frameworks (Next.js etc.): some values intentionally differ server vs client (random IDs, dates, locale/timezone formatting). For expected mismatches, wrap dynamic text with suppressHydrationWarning. Don't use it to hide real bugs. Don't overuse.

Incorrect: known mismatch warnings

function Timestamp() {
  return <span>{new Date().toLocaleString()}</span>
}

Correct: suppress expected mismatch only

function Timestamp() {
  return (
    <span suppressHydrationWarning>
      {new Date().toLocaleString()}
    </span>
  )
}

6.7 Use Activity Component for Show/Hide

Impact: MEDIUM (preserves state/DOM)

<Activity> preserves state/DOM for expensive components that toggle visibility often.

Usage:

import { Activity } from 'react'

function Dropdown({ isOpen }: Props) {
  return (
    <Activity mode={isOpen ? 'visible' : 'hidden'}>
      <ExpensiveMenu />
    </Activity>
  )
}

Avoids expensive re-renders + state loss.

6.8 Use defer or async on Script Tags

Impact: HIGH (eliminates render-blocking)

Script tags without defer/async block HTML parsing during download + execute. Delays First Contentful Paint + Time to Interactive.

  • defer: downloads in parallel, executes after HTML parse, keeps execution order
  • async: downloads in parallel, executes when ready, no order guarantee

Use defer for scripts depending on DOM or other scripts. Use async for independent scripts like analytics.

Incorrect: blocks rendering

export default function Document() {
  return (
    <html>
      <head>
        <script src="https://example.com/analytics.js" />
        <script src="/scripts/utils.js" />
      </head>
      <body>{/* content */}</body>
    </html>
  )
}

Correct: non-blocking

import Script from 'next/script'

export default function Page() {
  return (
    <>
      <Script src="https://example.com/analytics.js" strategy="afterInteractive" />
      <Script src="/scripts/utils.js" strategy="beforeInteractive" />
    </>
  )
}

Note: In Next.js, prefer next/script with strategy prop over raw <script>:

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 ternary (? :) instead of && when condition can be 0, NaN, or other falsy values that render.

Incorrect: renders "0" when count is 0

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

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>

6.10 Use React DOM Resource Hints

Impact: HIGH (reduces load time for critical resources)

React DOM has APIs to hint browser about needed resources. Useful in server components — start loading before client receives HTML.

  • prefetchDNS(href): resolve DNS for domain you'll connect to
  • preconnect(href): connection (DNS + TCP + TLS) to server
  • preload(href, options): fetch resource (stylesheet, font, script, image) you'll use soon
  • preloadModule(href): fetch ES module you'll use soon
  • preinit(href, options): fetch + eval stylesheet/script
  • preinitModule(href): fetch + eval ES module

Example: preconnect to 3rd-party APIs

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 + styles

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

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:

APIUse case
prefetchDNS3rd-party domains for later connection
preconnectAPIs/CDNs you'll fetch immediately
preloadCritical resources for current page
preloadModuleJS modules for likely next nav
preinitStylesheets/scripts that must execute early
preinitModuleES 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. Built-in isPending + auto-managed transitions.

Incorrect: manual loading state

function SearchResults() {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [isLoading, setIsLoading] = useState(false)

  const handleSearch = async (value: string) => {
    setIsLoading(true)
    setQuery(value)
    const data = await fetchResults(value)
    setResults(data)
    setIsLoading(false)
  }

  return (
    <>
      <input onChange={(e) => handleSearch(e.target.value)} />
      {isLoading && <Spinner />}
      <ResultsList results={results} />
    </>
  )
}

Correct: useTransition with built-in pending state

import { useTransition, useState } from 'react'

function SearchResults() {
  const [query, setQuery] = useState('')
  const [results, setResults] = useState([])
  const [isPending, startTransition] = useTransition()

  const handleSearch = (value: string) => {
    setQuery(value) // Update input immediately
    
    startTransition(async () => {
      // Fetch and update results
      const data = await fetchResults(value)
      setResults(data)
    })
  }

  return (
    <>
      <input onChange={(e) => handleSearch(e.target.value)} />
      {isPending && <Spinner />}
      <ResultsList results={results} />
    </>
  )
}

Benefits:

  • Auto pending state: no manual setIsLoading(true/false)
  • Error resilience: pending state resets even on throw
  • Better responsiveness: UI stays responsive during updates
  • Interrupt handling: new transitions auto-cancel pending ones

Reference: https://react.dev/reference/react/useTransition


7. JavaScript Performance

Impact: LOW-MEDIUM

Hot-path micro-opts add up.

7.1 Avoid Layout Thrashing

Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)

Don't interleave style writes with layout reads. Read layout property (offsetWidth, getBoundingClientRect(), getComputedStyle()) between style changes → browser forced to sync reflow.

OK: browser batches style changes

function updateElementStyles(element: HTMLElement) {
  // Each line invalidates style, but browser batches the recalculation
  element.style.width = '100px'
  element.style.height = '200px'
  element.style.backgroundColor = 'blue'
  element.style.border = '1px solid black'
}

Incorrect: interleaved reads/writes force reflows

function layoutThrashing(element: HTMLElement) {
  element.style.width = '100px'
  const width = element.offsetWidth  // Forces reflow
  element.style.height = '200px'
  const height = element.offsetHeight  // Forces another reflow
}

Correct: batch writes, then read once

function updateElementStyles(element: HTMLElement) {
  // Batch all writes together
  element.style.width = '100px'
  element.style.height = '200px'
  element.style.backgroundColor = 'blue'
  element.style.border = '1px solid black'
  
  // Read after all writes are done (single reflow)
  const { width, height } = element.getBoundingClientRect()
}

Correct: batch reads, then writes

function updateElementStyles(element: HTMLElement) {
  element.classList.add('highlighted-box')
  
  const { width, height } = element.getBoundingClientRect()
}

Better: CSS classes

React example:

// Incorrect: interleaving style changes with layout queries
function Box({ isHighlighted }: { isHighlighted: boolean }) {
  const ref = useRef<HTMLDivElement>(null)
  
  useEffect(() => {
    if (ref.current && isHighlighted) {
      ref.current.style.width = '100px'
      const width = ref.current.offsetWidth // Forces layout
      ref.current.style.height = '200px'
    }
  }, [isHighlighted])
  
  return <div ref={ref}>Content</div>
}

// Correct: toggle class
function Box({ isHighlighted }: { isHighlighted: boolean }) {
  return (
    <div className={isHighlighted ? 'highlighted-box' : ''}>
      Content
    </div>
  )
}

Prefer CSS classes over inline styles. CSS files cache in browser; classes = better separation + easier maintenance.

See this gist + CSS Triggers for layout-forcing ops.

7.2 Build Index Maps for Repeated Lookups

Impact: LOW-MEDIUM (1M ops to 2K ops)

Multiple .find() calls by same key → use Map.

Incorrect (O(n) per lookup):

function processOrders(orders: Order[], users: User[]) {
  return orders.map(order => ({
    ...order,
    user: users.find(u => u.id === order.userId)
  }))
}

Correct (O(1) per lookup):

function processOrders(orders: Order[], users: User[]) {
  const userById = new Map(users.map(u => [u.id, u]))

  return orders.map(order => ({
    ...order,
    user: userById.get(order.userId)
  }))
}

Build map once (O(n)) → all lookups O(1).

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

for (let i = 0; i < arr.length; i++) {
  process(obj.config.settings.value)
}

Correct: 1 lookup total

const value = obj.config.settings.value
const len = arr.length
for (let i = 0; i < len; i++) {
  process(value)
}

7.4 Cache Repeated Function Calls

Impact: MEDIUM (avoid redundant computation)

Use module-level Map to cache function results when same function called repeatedly with same inputs during render.

Incorrect: redundant computation

function ProjectList({ projects }: { projects: Project[] }) {
  return (
    <div>
      {projects.map(project => {
        // slugify() called 100+ times for same project names
        const slug = slugify(project.name)
        
        return <ProjectCard key={project.id} slug={slug} />
      })}
    </div>
  )
}

Correct: cached

// Module-level cache
const slugifyCache = new Map<string, string>()

function cachedSlugify(text: string): string {
  if (slugifyCache.has(text)) {
    return slugifyCache.get(text)!
  }
  const result = slugify(text)
  slugifyCache.set(text, result)
  return result
}

function ProjectList({ projects }: { projects: Project[] }) {
  return (
    <div>
      {projects.map(project => {
        // Computed only once per unique project name
        const slug = cachedSlugify(project.name)
        
        return <ProjectCard key={project.id} slug={slug} />
      })}
    </div>
  )
}

Simpler pattern for single-value functions:

let isLoggedInCache: boolean | null = null

function isLoggedIn(): boolean {
  if (isLoggedInCache !== null) {
    return isLoggedInCache
  }
  
  isLoggedInCache = document.cookie.includes('auth=')
  return isLoggedInCache
}

// Clear cache when auth changes
function onAuthChange() {
  isLoggedInCache = null
}

Use Map (not hook) — works everywhere: utilities, event handlers, not just 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, document.cookie = synchronous + expensive. Cache reads in memory.

Incorrect: reads storage on every call

function getTheme() {
  return localStorage.getItem('theme') ?? 'light'
}
// Called 10 times = 10 storage reads

Correct: Map cache

const storageCache = new Map<string, string | null>()

function getLocalStorage(key: string) {
  if (!storageCache.has(key)) {
    storageCache.set(key, localStorage.getItem(key))
  }
  return storageCache.get(key)
}

function setLocalStorage(key: string, value: string) {
  localStorage.setItem(key, value)
  storageCache.set(key, value)  // keep cache in sync
}

Use Map (not hook) — works everywhere: utilities, event handlers, not just components.

Cookie caching:

let cookieCache: Record<string, string> | null = null

function getCookie(name: string) {
  if (!cookieCache) {
    cookieCache = Object.fromEntries(
      document.cookie.split('; ').map(c => c.split('='))
    )
  }
  return cookieCache[name]
}

Important: invalidate on external changes

window.addEventListener('storage', (e) => {
  if (e.key) storageCache.delete(e.key)
})

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') {
    storageCache.clear()
  }
})

If storage can change externally (another tab, server-set cookies), invalidate:

7.6 Combine Multiple Array Iterations

Impact: LOW-MEDIUM (reduces iterations)

Multiple .filter() / .map() = multiple iterations. Combine into one loop.

Incorrect: 3 iterations

const admins = users.filter(u => u.isAdmin)
const testers = users.filter(u => u.isTester)
const inactive = users.filter(u => !u.isActive)

Correct: 1 iteration

const admins: User[] = []
const testers: User[] = []
const inactive: User[] = []

for (const user of users) {
  if (user.isAdmin) admins.push(user)
  if (user.isTester) testers.push(user)
  if (!user.isActive) inactive.push(user)
}

7.7 Defer Non-Critical Work with requestIdleCallback

Impact: MEDIUM (keeps UI responsive during background tasks)

requestIdleCallback() schedules non-critical work during browser idle. Frees main thread for interactions + animations → less jank, better perceived perf.

Incorrect: blocks main thread during user interaction

function handleSearch(query: string) {
  const results = searchItems(query)
  setResults(results)

  // These block the main thread immediately
  analytics.track('search', { query })
  saveToRecentSearches(query)
  prefetchTopResults(results.slice(0, 3))
}

Correct: defers non-critical work to idle

function handleSearch(query: string) {
  const results = searchItems(query)
  setResults(results)

  // Defer non-critical work to idle periods
  requestIdleCallback(() => {
    analytics.track('search', { query })
  })

  requestIdleCallback(() => {
    saveToRecentSearches(query)
  })

  requestIdleCallback(() => {
    prefetchTopResults(results.slice(0, 3))
  })
}

With timeout for required work:

// Ensure analytics fires within 2 seconds even if browser stays busy
requestIdleCallback(
  () => analytics.track('page_view', { path: location.pathname }),
  { timeout: 2000 }
)

Chunking large tasks:

function processLargeDataset(items: Item[]) {
  let index = 0

  function processChunk(deadline: IdleDeadline) {
    // Process items while we have idle time (aim for <50ms chunks)
    while (index < items.length && deadline.timeRemaining() > 0) {
      processItem(items[index])
      index++
    }

    // Schedule next chunk if more items remain
    if (index < items.length) {
      requestIdleCallback(processChunk)
    }
  }

  requestIdleCallback(processChunk)
}

Fallback for unsupported browsers:

const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))

scheduleIdleWork(() => {
  // Non-critical work
})

Use for:

  • Analytics + telemetry
  • Save state to localStorage/IndexedDB
  • Prefetch resources for likely next actions
  • Non-urgent data transforms
  • Lazy init of non-critical features

Don't use for:

  • User-initiated actions needing immediate feedback
  • Render updates user is waiting for
  • Time-sensitive ops

7.8 Early Length Check for Array Comparisons

Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)

Comparing arrays with expensive ops (sort, deep eq, serialize) → check lengths first. Lengths differ → arrays can't be equal.

Valuable in hot paths (event handlers, render loops).

Incorrect: always runs expensive comparison

function hasChanges(current: string[], original: string[]) {
  // Always sorts and joins, even when lengths differ
  return current.sort().join() !== original.sort().join()
}

Two O(n log n) sorts run even when current.length is 5 and original.length is 100. Plus join + string compare overhead.

Correct (O(1) length check first):

function hasChanges(current: string[], original: string[]) {
  // Early return if lengths differ
  if (current.length !== original.length) {
    return true
  }
  // Only sort when lengths match
  const currentSorted = current.toSorted()
  const originalSorted = original.toSorted()
  for (let i = 0; i < currentSorted.length; i++) {
    if (currentSorted[i] !== originalSorted[i]) {
      return true
    }
  }
  return false
}

Better because:

  • No sort/join overhead when lengths differ
  • No memory for joined strings (matters for big arrays)
  • No mutation of originals
  • Returns on first diff

7.9 Early Return from Functions

Impact: LOW-MEDIUM (avoids unnecessary computation)

Return early when result determined → skip unnecessary processing.

Incorrect: processes all items after finding answer

function validateUsers(users: User[]) {
  let hasError = false
  let errorMessage = ''
  
  for (const user of users) {
    if (!user.email) {
      hasError = true
      errorMessage = 'Email required'
    }
    if (!user.name) {
      hasError = true
      errorMessage = 'Name required'
    }
    // Continues checking all users even after error found
  }
  
  return hasError ? { valid: false, error: errorMessage } : { valid: true }
}

Correct: returns on first error

function validateUsers(users: User[]) {
  for (const user of users) {
    if (!user.email) {
      return { valid: false, error: 'Email required' }
    }
    if (!user.name) {
      return { valid: false, error: 'Name required' }
    }
  }

  return { valid: true }
}

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

function Highlighter({ text, query }: Props) {
  const regex = new RegExp(`(${query})`, 'gi')
  const parts = text.split(regex)
  return <>{parts.map((part, i) => ...)}</>
}

Correct: memoize or hoist

const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/

function Highlighter({ text, query }: Props) {
  const regex = useMemo(
    () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
    [query]
  )
  const parts = text.split(regex)
  return <>{parts.map((part, i) => ...)}</>
}

Warning: global regex has mutable state

const regex = /foo/g
regex.test('foo')  // true, lastIndex = 3
regex.test('foo')  // false, lastIndex = 0

Global regex (/g) has mutable lastIndex:

7.11 Use flatMap to Map and Filter in One Pass

Impact: LOW-MEDIUM (eliminates intermediate array)

.map().filter(Boolean) = intermediate array + 2 iterations. .flatMap() transforms + filters in one pass.

Incorrect: 2 iterations, intermediate array

const userNames = users
  .map(user => user.isActive ? user.name : null)
  .filter(Boolean)

Correct: 1 iteration, no intermediate

const userNames = users.flatMap(user =>
  user.isActive ? [user.name] : []
)

More examples:

// Extract valid emails from responses
// Before
const emails = responses
  .map(r => r.success ? r.data.email : null)
  .filter(Boolean)

// After
const emails = responses.flatMap(r =>
  r.success ? [r.data.email] : []
)

// Parse and filter valid numbers
// Before
const numbers = strings
  .map(s => parseInt(s, 10))
  .filter(n => !isNaN(n))

// After
const numbers = strings.flatMap(s => {
  const n = parseInt(s, 10)
  return isNaN(n) ? [] : [n]
})

When to use:

  • Transform items + filter some out
  • Conditional mapping where some inputs produce no output
  • Parsing/validating where invalid inputs should skip

7.12 Use Loop for Min/Max Instead of Sort

Impact: LOW (O(n) instead of O(n log n))

Finding smallest/largest = single pass. Sort = wasteful + slower.

Incorrect (O(n log n) - sort to find latest):

interface Project {
  id: string
  name: string
  updatedAt: number
}

function getLatestProject(projects: Project[]) {
  const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
  return sorted[0]
}

Sorts whole array just to find max.

Incorrect (O(n log n) - sort for oldest + newest):

function getOldestAndNewest(projects: Project[]) {
  const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
  return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
}

Still sorts when only min/max needed.

Correct (O(n) - single loop):

function getLatestProject(projects: Project[]) {
  if (projects.length === 0) return null
  
  let latest = projects[0]
  
  for (let i = 1; i < projects.length; i++) {
    if (projects[i].updatedAt > latest.updatedAt) {
      latest = projects[i]
    }
  }
  
  return latest
}

function getOldestAndNewest(projects: Project[]) {
  if (projects.length === 0) return { oldest: null, newest: null }
  
  let oldest = projects[0]
  let newest = projects[0]
  
  for (let i = 1; i < projects.length; i++) {
    if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
    if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
  }
  
  return { oldest, newest }
}

Single pass, no copy, no sort.

Alt: Math.min/Math.max for small arrays

const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)

Works for small arrays — slower or throws on very large due to spread limits. Max array length ~124000 in Chrome 143, ~638000 in Safari 18 — varies, see the fiddle. Use loop 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):

const allowedIds = ['a', 'b', 'c', ...]
items.filter(item => allowedIds.includes(item.id))

Correct (O(1) per check):

const allowedIds = new Set(['a', 'b', 'c', ...])
items.filter(item => allowedIds.has(item.id))

7.14 Use toSorted() Instead of sort() for Immutability

Impact: MEDIUM-HIGH (prevents mutation bugs in React state)

.sort() mutates in place → bugs with React state/props. Use .toSorted() for new sorted array.

Incorrect: mutates original

function UserList({ users }: { users: User[] }) {
  // Mutates the users prop array!
  const sorted = useMemo(
    () => users.sort((a, b) => a.name.localeCompare(b.name)),
    [users]
  )
  return <div>{sorted.map(renderUser)}</div>
}

Correct: new array

function UserList({ users }: { users: User[] }) {
  // Creates new sorted array, original unchanged
  const sorted = useMemo(
    () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
    [users]
  )
  return <div>{sorted.map(renderUser)}</div>
}

Why it matters in React:

  1. Props/state mutations break React's immutability model — React treats them as read-only
  2. Stale closure bugs — mutating arrays inside closures (callbacks, effects) → unexpected behavior

Browser support: fallback for older browsers

// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)

.toSorted() in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). Older envs → spread:

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 needing 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 have no stable identity — identity changes every render. Don't include useEffectEvent return in useEffect deps. Keep reactive values as deps; call Effect Event from effect body or subscriptions created by it.

Incorrect: Effect Event added as dep

import { useEffect, useEffectEvent } from 'react'

function ChatRoom({ roomId, onConnected }: {
  roomId: string
  onConnected: () => void
}) {
  const handleConnected = useEffectEvent(onConnected)

  useEffect(() => {
    const connection = createConnection(roomId)
    connection.on('connected', handleConnected)
    connection.connect()

    return () => connection.disconnect()
  }, [roomId, handleConnected])
}

Effect Event in deps = effect re-runs every render + triggers React Hooks lint rule.

Correct: depend on reactive values, not Effect Event

import { useEffect, useEffectEvent } from 'react'

function ChatRoom({ roomId, onConnected }: {
  roomId: string
  onConnected: () => void
}) {
  const handleConnected = useEffectEvent(onConnected)

  useEffect(() => {
    const connection = createConnection(roomId)
    connection.on('connected', handleConnected)
    connection.connect()

    return () => connection.disconnect()
  }, [roomId])
}

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)

Don't put app-wide once-per-load init inside useEffect([]). Components remount; effects re-run. Use module-level guard or top-level init in entry module.

Incorrect: runs twice in dev, re-runs on remount

function Comp() {
  useEffect(() => {
    loadFromStorage()
    checkAuthToken()
  }, [])

  // ...
}

Correct: once per app load

let didInit = false

function Comp() {
  useEffect(() => {
    if (didInit) return
    didInit = true
    loadFromStorage()
    checkAuthToken()
  }, [])

  // ...
}

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 for effects that shouldn't re-subscribe on callback changes.

Incorrect: re-subscribes every render

function useWindowEvent(event: string, handler: (e) => void) {
  useEffect(() => {
    window.addEventListener(event, handler)
    return () => window.removeEventListener(event, handler)
  }, [event, handler])
}

Correct: stable subscription

import { useEffectEvent } from 'react'

function useWindowEvent(event: string, handler: (e) => void) {
  const onEvent = useEffectEvent(handler)

  useEffect(() => {
    window.addEventListener(event, onEvent)
    return () => window.removeEventListener(event, onEvent)
  }, [event])
}

Alt: useEffectEvent on latest React:

useEffectEvent = cleaner API: stable function ref that always calls latest handler.

8.4 useEffectEvent for Stable Callback Refs

Impact: LOW (prevents effect re-runs)

Access latest values in callbacks without adding them to dep arrays. Prevents effect re-runs + avoids stale closures.

Incorrect: effect re-runs on every callback change

function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
  const [query, setQuery] = useState('')

  useEffect(() => {
    const timeout = setTimeout(() => onSearch(query), 300)
    return () => clearTimeout(timeout)
  }, [query, onSearch])
}

Correct: React's useEffectEvent

import { useEffectEvent } from 'react';

function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
  const [query, setQuery] = useState('')
  const onSearchEvent = useEffectEvent(onSearch)

  useEffect(() => {
    const timeout = setTimeout(() => onSearchEvent(query), 300)
    return () => clearTimeout(timeout)
  }, [query])
}

References

  1. https://react.dev
  2. https://nextjs.org
  3. https://swr.vercel.app
  4. https://github.com/shuding/better-all
  5. https://github.com/isaacs/node-lru-cache
  6. https://vercel.com/blog/how-we-optimized-package-imports-in-next-js
  7. https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.