beth-copilot 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +224 -0
  2. package/bin/cli.js +223 -0
  3. package/package.json +36 -0
  4. package/templates/.github/agents/beth.agent.md +279 -0
  5. package/templates/.github/agents/developer.agent.md +493 -0
  6. package/templates/.github/agents/frontend-engineer.agent.md +556 -0
  7. package/templates/.github/agents/product-manager.agent.md +253 -0
  8. package/templates/.github/agents/researcher.agent.md +319 -0
  9. package/templates/.github/agents/security-reviewer.agent.md +452 -0
  10. package/templates/.github/agents/tester.agent.md +477 -0
  11. package/templates/.github/agents/ux-designer.agent.md +374 -0
  12. package/templates/.github/copilot-instructions.md +191 -0
  13. package/templates/.github/skills/framer-components/SKILL.md +564 -0
  14. package/templates/.github/skills/prd/SKILL.md +244 -0
  15. package/templates/.github/skills/security-analysis/SKILL.md +799 -0
  16. package/templates/.github/skills/shadcn-ui/SKILL.md +562 -0
  17. package/templates/.github/skills/vercel-react-best-practices/AGENTS.md +2516 -0
  18. package/templates/.github/skills/vercel-react-best-practices/SKILL.md +125 -0
  19. package/templates/.github/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +55 -0
  20. package/templates/.github/skills/vercel-react-best-practices/rules/advanced-use-latest.md +49 -0
  21. package/templates/.github/skills/vercel-react-best-practices/rules/async-api-routes.md +38 -0
  22. package/templates/.github/skills/vercel-react-best-practices/rules/async-defer-await.md +80 -0
  23. package/templates/.github/skills/vercel-react-best-practices/rules/async-dependencies.md +36 -0
  24. package/templates/.github/skills/vercel-react-best-practices/rules/async-parallel.md +28 -0
  25. package/templates/.github/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +99 -0
  26. package/templates/.github/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +59 -0
  27. package/templates/.github/skills/vercel-react-best-practices/rules/bundle-conditional.md +31 -0
  28. package/templates/.github/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +49 -0
  29. package/templates/.github/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +35 -0
  30. package/templates/.github/skills/vercel-react-best-practices/rules/bundle-preload.md +50 -0
  31. package/templates/.github/skills/vercel-react-best-practices/rules/client-event-listeners.md +74 -0
  32. package/templates/.github/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +71 -0
  33. package/templates/.github/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +48 -0
  34. package/templates/.github/skills/vercel-react-best-practices/rules/client-swr-dedup.md +56 -0
  35. package/templates/.github/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +57 -0
  36. package/templates/.github/skills/vercel-react-best-practices/rules/js-cache-function-results.md +80 -0
  37. package/templates/.github/skills/vercel-react-best-practices/rules/js-cache-property-access.md +28 -0
  38. package/templates/.github/skills/vercel-react-best-practices/rules/js-cache-storage.md +70 -0
  39. package/templates/.github/skills/vercel-react-best-practices/rules/js-combine-iterations.md +32 -0
  40. package/templates/.github/skills/vercel-react-best-practices/rules/js-early-exit.md +50 -0
  41. package/templates/.github/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +45 -0
  42. package/templates/.github/skills/vercel-react-best-practices/rules/js-index-maps.md +37 -0
  43. package/templates/.github/skills/vercel-react-best-practices/rules/js-length-check-first.md +49 -0
  44. package/templates/.github/skills/vercel-react-best-practices/rules/js-min-max-loop.md +82 -0
  45. package/templates/.github/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +24 -0
  46. package/templates/.github/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +57 -0
  47. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-activity.md +26 -0
  48. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
  49. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +40 -0
  50. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +38 -0
  51. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
  52. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
  53. package/templates/.github/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +28 -0
  54. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +39 -0
  55. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-dependencies.md +45 -0
  56. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-derived-state.md +29 -0
  57. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +74 -0
  58. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
  59. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-memo.md +44 -0
  60. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +35 -0
  61. package/templates/.github/skills/vercel-react-best-practices/rules/rerender-transitions.md +40 -0
  62. package/templates/.github/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +73 -0
  63. package/templates/.github/skills/vercel-react-best-practices/rules/server-auth-actions.md +96 -0
  64. package/templates/.github/skills/vercel-react-best-practices/rules/server-cache-lru.md +41 -0
  65. package/templates/.github/skills/vercel-react-best-practices/rules/server-cache-react.md +76 -0
  66. package/templates/.github/skills/vercel-react-best-practices/rules/server-dedup-props.md +65 -0
  67. package/templates/.github/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +83 -0
  68. package/templates/.github/skills/vercel-react-best-practices/rules/server-serialization.md +38 -0
  69. package/templates/.github/skills/web-design-guidelines/SKILL.md +39 -0
  70. package/templates/AGENTS.md +70 -0
  71. package/templates/Backlog.md +80 -0
  72. package/templates/mcp.json.example +9 -0
@@ -0,0 +1,2516 @@
1
+ # React Best Practices
2
+
3
+ **Version 1.0.0**
4
+ Vercel Engineering
5
+ January 2026
6
+
7
+ > **Note:**
8
+ > This document is mainly for agents and LLMs to follow when maintaining,
9
+ > generating, or refactoring React and Next.js codebases at Vercel. Humans
10
+ > may also find it useful, but guidance here is optimized for automation
11
+ > and consistency by AI-assisted workflows.
12
+
13
+ ---
14
+
15
+ ## Abstract
16
+
17
+ Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.
18
+
19
+ ---
20
+
21
+ ## Table of Contents
22
+
23
+ 1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**
24
+ - 1.1 [Defer Await Until Needed](#11-defer-await-until-needed)
25
+ - 1.2 [Dependency-Based Parallelization](#12-dependency-based-parallelization)
26
+ - 1.3 [Prevent Waterfall Chains in API Routes](#13-prevent-waterfall-chains-in-api-routes)
27
+ - 1.4 [Promise.all() for Independent Operations](#14-promiseall-for-independent-operations)
28
+ - 1.5 [Strategic Suspense Boundaries](#15-strategic-suspense-boundaries)
29
+ 2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**
30
+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)
31
+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)
32
+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)
33
+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)
34
+ - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent)
35
+ 3. [Server-Side Performance](#3-server-side-performance) — **HIGH**
36
+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)
37
+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)
38
+ - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching)
39
+ - 3.4 [Minimize Serialization at RSC Boundaries](#34-minimize-serialization-at-rsc-boundaries)
40
+ - 3.5 [Parallel Data Fetching with Component Composition](#35-parallel-data-fetching-with-component-composition)
41
+ - 3.6 [Per-Request Deduplication with React.cache()](#36-per-request-deduplication-with-reactcache)
42
+ - 3.7 [Use after() for Non-Blocking Operations](#37-use-after-for-non-blocking-operations)
43
+ 4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**
44
+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)
45
+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)
46
+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)
47
+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)
48
+ 5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**
49
+ - 5.1 [Defer State Reads to Usage Point](#51-defer-state-reads-to-usage-point)
50
+ - 5.2 [Extract to Memoized Components](#52-extract-to-memoized-components)
51
+ - 5.3 [Narrow Effect Dependencies](#53-narrow-effect-dependencies)
52
+ - 5.4 [Subscribe to Derived State](#54-subscribe-to-derived-state)
53
+ - 5.5 [Use Functional setState Updates](#55-use-functional-setstate-updates)
54
+ - 5.6 [Use Lazy State Initialization](#56-use-lazy-state-initialization)
55
+ - 5.7 [Use Transitions for Non-Urgent Updates](#57-use-transitions-for-non-urgent-updates)
56
+ 6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**
57
+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)
58
+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)
59
+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)
60
+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)
61
+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)
62
+ - 6.6 [Use Activity Component for Show/Hide](#66-use-activity-component-for-showhide)
63
+ - 6.7 [Use Explicit Conditional Rendering](#67-use-explicit-conditional-rendering)
64
+ 7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**
65
+ - 7.1 [Batch DOM CSS Changes](#71-batch-dom-css-changes)
66
+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)
67
+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)
68
+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)
69
+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)
70
+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)
71
+ - 7.7 [Early Length Check for Array Comparisons](#77-early-length-check-for-array-comparisons)
72
+ - 7.8 [Early Return from Functions](#78-early-return-from-functions)
73
+ - 7.9 [Hoist RegExp Creation](#79-hoist-regexp-creation)
74
+ - 7.10 [Use Loop for Min/Max Instead of Sort](#710-use-loop-for-minmax-instead-of-sort)
75
+ - 7.11 [Use Set/Map for O(1) Lookups](#711-use-setmap-for-o1-lookups)
76
+ - 7.12 [Use toSorted() Instead of sort() for Immutability](#712-use-tosorted-instead-of-sort-for-immutability)
77
+ 8. [Advanced Patterns](#8-advanced-patterns) — **LOW**
78
+ - 8.1 [Store Event Handlers in Refs](#81-store-event-handlers-in-refs)
79
+ - 8.2 [useLatest for Stable Callback Refs](#82-uselatest-for-stable-callback-refs)
80
+
81
+ ---
82
+
83
+ ## 1. Eliminating Waterfalls
84
+
85
+ **Impact: CRITICAL**
86
+
87
+ Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
88
+
89
+ ### 1.1 Defer Await Until Needed
90
+
91
+ **Impact: HIGH (avoids blocking unused code paths)**
92
+
93
+ Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
94
+
95
+ **Incorrect: blocks both branches**
96
+
97
+ ```typescript
98
+ async function handleRequest(userId: string, skipProcessing: boolean) {
99
+ const userData = await fetchUserData(userId)
100
+
101
+ if (skipProcessing) {
102
+ // Returns immediately but still waited for userData
103
+ return { skipped: true }
104
+ }
105
+
106
+ // Only this branch uses userData
107
+ return processUserData(userData)
108
+ }
109
+ ```
110
+
111
+ **Correct: only blocks when needed**
112
+
113
+ ```typescript
114
+ async function handleRequest(userId: string, skipProcessing: boolean) {
115
+ if (skipProcessing) {
116
+ // Returns immediately without waiting
117
+ return { skipped: true }
118
+ }
119
+
120
+ // Fetch only when needed
121
+ const userData = await fetchUserData(userId)
122
+ return processUserData(userData)
123
+ }
124
+ ```
125
+
126
+ **Another example: early return optimization**
127
+
128
+ ```typescript
129
+ // Incorrect: always fetches permissions
130
+ async function updateResource(resourceId: string, userId: string) {
131
+ const permissions = await fetchPermissions(userId)
132
+ const resource = await getResource(resourceId)
133
+
134
+ if (!resource) {
135
+ return { error: 'Not found' }
136
+ }
137
+
138
+ if (!permissions.canEdit) {
139
+ return { error: 'Forbidden' }
140
+ }
141
+
142
+ return await updateResourceData(resource, permissions)
143
+ }
144
+
145
+ // Correct: fetches only when needed
146
+ async function updateResource(resourceId: string, userId: string) {
147
+ const resource = await getResource(resourceId)
148
+
149
+ if (!resource) {
150
+ return { error: 'Not found' }
151
+ }
152
+
153
+ const permissions = await fetchPermissions(userId)
154
+
155
+ if (!permissions.canEdit) {
156
+ return { error: 'Forbidden' }
157
+ }
158
+
159
+ return await updateResourceData(resource, permissions)
160
+ }
161
+ ```
162
+
163
+ This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
164
+
165
+ ### 1.2 Dependency-Based Parallelization
166
+
167
+ **Impact: CRITICAL (2-10× improvement)**
168
+
169
+ For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
170
+
171
+ **Incorrect: profile waits for config unnecessarily**
172
+
173
+ ```typescript
174
+ const [user, config] = await Promise.all([
175
+ fetchUser(),
176
+ fetchConfig()
177
+ ])
178
+ const profile = await fetchProfile(user.id)
179
+ ```
180
+
181
+ **Correct: config and profile run in parallel**
182
+
183
+ ```typescript
184
+ import { all } from 'better-all'
185
+
186
+ const { user, config, profile } = await all({
187
+ async user() { return fetchUser() },
188
+ async config() { return fetchConfig() },
189
+ async profile() {
190
+ return fetchProfile((await this.$.user).id)
191
+ }
192
+ })
193
+ ```
194
+
195
+ Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
196
+
197
+ ### 1.3 Prevent Waterfall Chains in API Routes
198
+
199
+ **Impact: CRITICAL (2-10× improvement)**
200
+
201
+ In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
202
+
203
+ **Incorrect: config waits for auth, data waits for both**
204
+
205
+ ```typescript
206
+ export async function GET(request: Request) {
207
+ const session = await auth()
208
+ const config = await fetchConfig()
209
+ const data = await fetchData(session.user.id)
210
+ return Response.json({ data, config })
211
+ }
212
+ ```
213
+
214
+ **Correct: auth and config start immediately**
215
+
216
+ ```typescript
217
+ export async function GET(request: Request) {
218
+ const sessionPromise = auth()
219
+ const configPromise = fetchConfig()
220
+ const session = await sessionPromise
221
+ const [config, data] = await Promise.all([
222
+ configPromise,
223
+ fetchData(session.user.id)
224
+ ])
225
+ return Response.json({ data, config })
226
+ }
227
+ ```
228
+
229
+ For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
230
+
231
+ ### 1.4 Promise.all() for Independent Operations
232
+
233
+ **Impact: CRITICAL (2-10× improvement)**
234
+
235
+ When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
236
+
237
+ **Incorrect: sequential execution, 3 round trips**
238
+
239
+ ```typescript
240
+ const user = await fetchUser()
241
+ const posts = await fetchPosts()
242
+ const comments = await fetchComments()
243
+ ```
244
+
245
+ **Correct: parallel execution, 1 round trip**
246
+
247
+ ```typescript
248
+ const [user, posts, comments] = await Promise.all([
249
+ fetchUser(),
250
+ fetchPosts(),
251
+ fetchComments()
252
+ ])
253
+ ```
254
+
255
+ ### 1.5 Strategic Suspense Boundaries
256
+
257
+ **Impact: HIGH (faster initial paint)**
258
+
259
+ Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
260
+
261
+ **Incorrect: wrapper blocked by data fetching**
262
+
263
+ ```tsx
264
+ async function Page() {
265
+ const data = await fetchData() // Blocks entire page
266
+
267
+ return (
268
+ <div>
269
+ <div>Sidebar</div>
270
+ <div>Header</div>
271
+ <div>
272
+ <DataDisplay data={data} />
273
+ </div>
274
+ <div>Footer</div>
275
+ </div>
276
+ )
277
+ }
278
+ ```
279
+
280
+ The entire layout waits for data even though only the middle section needs it.
281
+
282
+ **Correct: wrapper shows immediately, data streams in**
283
+
284
+ ```tsx
285
+ function Page() {
286
+ return (
287
+ <div>
288
+ <div>Sidebar</div>
289
+ <div>Header</div>
290
+ <div>
291
+ <Suspense fallback={<Skeleton />}>
292
+ <DataDisplay />
293
+ </Suspense>
294
+ </div>
295
+ <div>Footer</div>
296
+ </div>
297
+ )
298
+ }
299
+
300
+ async function DataDisplay() {
301
+ const data = await fetchData() // Only blocks this component
302
+ return <div>{data.content}</div>
303
+ }
304
+ ```
305
+
306
+ Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
307
+
308
+ **Alternative: share promise across components**
309
+
310
+ ```tsx
311
+ function Page() {
312
+ // Start fetch immediately, but don't await
313
+ const dataPromise = fetchData()
314
+
315
+ return (
316
+ <div>
317
+ <div>Sidebar</div>
318
+ <div>Header</div>
319
+ <Suspense fallback={<Skeleton />}>
320
+ <DataDisplay dataPromise={dataPromise} />
321
+ <DataSummary dataPromise={dataPromise} />
322
+ </Suspense>
323
+ <div>Footer</div>
324
+ </div>
325
+ )
326
+ }
327
+
328
+ function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
329
+ const data = use(dataPromise) // Unwraps the promise
330
+ return <div>{data.content}</div>
331
+ }
332
+
333
+ function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
334
+ const data = use(dataPromise) // Reuses the same promise
335
+ return <div>{data.summary}</div>
336
+ }
337
+ ```
338
+
339
+ Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
340
+
341
+ **When NOT to use this pattern:**
342
+
343
+ - Critical data needed for layout decisions (affects positioning)
344
+
345
+ - SEO-critical content above the fold
346
+
347
+ - Small, fast queries where suspense overhead isn't worth it
348
+
349
+ - When you want to avoid layout shift (loading → content jump)
350
+
351
+ **Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
352
+
353
+ ---
354
+
355
+ ## 2. Bundle Size Optimization
356
+
357
+ **Impact: CRITICAL**
358
+
359
+ Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
360
+
361
+ ### 2.1 Avoid Barrel File Imports
362
+
363
+ **Impact: CRITICAL (200-800ms import cost, slow builds)**
364
+
365
+ Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
366
+
367
+ Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
368
+
369
+ **Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
370
+
371
+ **Incorrect: imports entire library**
372
+
373
+ ```tsx
374
+ import { Check, X, Menu } from 'lucide-react'
375
+ // Loads 1,583 modules, takes ~2.8s extra in dev
376
+ // Runtime cost: 200-800ms on every cold start
377
+
378
+ import { Button, TextField } from '@mui/material'
379
+ // Loads 2,225 modules, takes ~4.2s extra in dev
380
+ ```
381
+
382
+ **Correct: imports only what you need**
383
+
384
+ ```tsx
385
+ import Check from 'lucide-react/dist/esm/icons/check'
386
+ import X from 'lucide-react/dist/esm/icons/x'
387
+ import Menu from 'lucide-react/dist/esm/icons/menu'
388
+ // Loads only 3 modules (~2KB vs ~1MB)
389
+
390
+ import Button from '@mui/material/Button'
391
+ import TextField from '@mui/material/TextField'
392
+ // Loads only what you use
393
+ ```
394
+
395
+ **Alternative: Next.js 13.5+**
396
+
397
+ ```js
398
+ // next.config.js - use optimizePackageImports
399
+ module.exports = {
400
+ experimental: {
401
+ optimizePackageImports: ['lucide-react', '@mui/material']
402
+ }
403
+ }
404
+
405
+ // Then you can keep the ergonomic barrel imports:
406
+ import { Check, X, Menu } from 'lucide-react'
407
+ // Automatically transformed to direct imports at build time
408
+ ```
409
+
410
+ Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
411
+
412
+ Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
413
+
414
+ Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
415
+
416
+ ### 2.2 Conditional Module Loading
417
+
418
+ **Impact: HIGH (loads large data only when needed)**
419
+
420
+ Load large data or modules only when a feature is activated.
421
+
422
+ **Example: lazy-load animation frames**
423
+
424
+ ```tsx
425
+ function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
426
+ const [frames, setFrames] = useState<Frame[] | null>(null)
427
+
428
+ useEffect(() => {
429
+ if (enabled && !frames && typeof window !== 'undefined') {
430
+ import('./animation-frames.js')
431
+ .then(mod => setFrames(mod.frames))
432
+ .catch(() => setEnabled(false))
433
+ }
434
+ }, [enabled, frames, setEnabled])
435
+
436
+ if (!frames) return <Skeleton />
437
+ return <Canvas frames={frames} />
438
+ }
439
+ ```
440
+
441
+ The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
442
+
443
+ ### 2.3 Defer Non-Critical Third-Party Libraries
444
+
445
+ **Impact: MEDIUM (loads after hydration)**
446
+
447
+ Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
448
+
449
+ **Incorrect: blocks initial bundle**
450
+
451
+ ```tsx
452
+ import { Analytics } from '@vercel/analytics/react'
453
+
454
+ export default function RootLayout({ children }) {
455
+ return (
456
+ <html>
457
+ <body>
458
+ {children}
459
+ <Analytics />
460
+ </body>
461
+ </html>
462
+ )
463
+ }
464
+ ```
465
+
466
+ **Correct: loads after hydration**
467
+
468
+ ```tsx
469
+ import dynamic from 'next/dynamic'
470
+
471
+ const Analytics = dynamic(
472
+ () => import('@vercel/analytics/react').then(m => m.Analytics),
473
+ { ssr: false }
474
+ )
475
+
476
+ export default function RootLayout({ children }) {
477
+ return (
478
+ <html>
479
+ <body>
480
+ {children}
481
+ <Analytics />
482
+ </body>
483
+ </html>
484
+ )
485
+ }
486
+ ```
487
+
488
+ ### 2.4 Dynamic Imports for Heavy Components
489
+
490
+ **Impact: CRITICAL (directly affects TTI and LCP)**
491
+
492
+ Use `next/dynamic` to lazy-load large components not needed on initial render.
493
+
494
+ **Incorrect: Monaco bundles with main chunk ~300KB**
495
+
496
+ ```tsx
497
+ import { MonacoEditor } from './monaco-editor'
498
+
499
+ function CodePanel({ code }: { code: string }) {
500
+ return <MonacoEditor value={code} />
501
+ }
502
+ ```
503
+
504
+ **Correct: Monaco loads on demand**
505
+
506
+ ```tsx
507
+ import dynamic from 'next/dynamic'
508
+
509
+ const MonacoEditor = dynamic(
510
+ () => import('./monaco-editor').then(m => m.MonacoEditor),
511
+ { ssr: false }
512
+ )
513
+
514
+ function CodePanel({ code }: { code: string }) {
515
+ return <MonacoEditor value={code} />
516
+ }
517
+ ```
518
+
519
+ ### 2.5 Preload Based on User Intent
520
+
521
+ **Impact: MEDIUM (reduces perceived latency)**
522
+
523
+ Preload heavy bundles before they're needed to reduce perceived latency.
524
+
525
+ **Example: preload on hover/focus**
526
+
527
+ ```tsx
528
+ function EditorButton({ onClick }: { onClick: () => void }) {
529
+ const preload = () => {
530
+ if (typeof window !== 'undefined') {
531
+ void import('./monaco-editor')
532
+ }
533
+ }
534
+
535
+ return (
536
+ <button
537
+ onMouseEnter={preload}
538
+ onFocus={preload}
539
+ onClick={onClick}
540
+ >
541
+ Open Editor
542
+ </button>
543
+ )
544
+ }
545
+ ```
546
+
547
+ **Example: preload when feature flag is enabled**
548
+
549
+ ```tsx
550
+ function FlagsProvider({ children, flags }: Props) {
551
+ useEffect(() => {
552
+ if (flags.editorEnabled && typeof window !== 'undefined') {
553
+ void import('./monaco-editor').then(mod => mod.init())
554
+ }
555
+ }, [flags.editorEnabled])
556
+
557
+ return <FlagsContext.Provider value={flags}>
558
+ {children}
559
+ </FlagsContext.Provider>
560
+ }
561
+ ```
562
+
563
+ The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
564
+
565
+ ---
566
+
567
+ ## 3. Server-Side Performance
568
+
569
+ **Impact: HIGH**
570
+
571
+ Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
572
+
573
+ ### 3.1 Authenticate Server Actions Like API Routes
574
+
575
+ **Impact: CRITICAL (prevents unauthorized access to server mutations)**
576
+
577
+ Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.
578
+
579
+ Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."
580
+
581
+ **Incorrect: no authentication check**
582
+
583
+ ```typescript
584
+ 'use server'
585
+
586
+ export async function deleteUser(userId: string) {
587
+ // Anyone can call this! No auth check
588
+ await db.user.delete({ where: { id: userId } })
589
+ return { success: true }
590
+ }
591
+ ```
592
+
593
+ **Correct: authentication inside the action**
594
+
595
+ ```typescript
596
+ 'use server'
597
+
598
+ import { verifySession } from '@/lib/auth'
599
+ import { unauthorized } from '@/lib/errors'
600
+
601
+ export async function deleteUser(userId: string) {
602
+ // Always check auth inside the action
603
+ const session = await verifySession()
604
+
605
+ if (!session) {
606
+ throw unauthorized('Must be logged in')
607
+ }
608
+
609
+ // Check authorization too
610
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
611
+ throw unauthorized('Cannot delete other users')
612
+ }
613
+
614
+ await db.user.delete({ where: { id: userId } })
615
+ return { success: true }
616
+ }
617
+ ```
618
+
619
+ **With input validation:**
620
+
621
+ ```typescript
622
+ 'use server'
623
+
624
+ import { verifySession } from '@/lib/auth'
625
+ import { z } from 'zod'
626
+
627
+ const updateProfileSchema = z.object({
628
+ userId: z.string().uuid(),
629
+ name: z.string().min(1).max(100),
630
+ email: z.string().email()
631
+ })
632
+
633
+ export async function updateProfile(data: unknown) {
634
+ // Validate input first
635
+ const validated = updateProfileSchema.parse(data)
636
+
637
+ // Then authenticate
638
+ const session = await verifySession()
639
+ if (!session) {
640
+ throw new Error('Unauthorized')
641
+ }
642
+
643
+ // Then authorize
644
+ if (session.user.id !== validated.userId) {
645
+ throw new Error('Can only update own profile')
646
+ }
647
+
648
+ // Finally perform the mutation
649
+ await db.user.update({
650
+ where: { id: validated.userId },
651
+ data: {
652
+ name: validated.name,
653
+ email: validated.email
654
+ }
655
+ })
656
+
657
+ return { success: true }
658
+ }
659
+ ```
660
+
661
+ Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
662
+
663
+ ### 3.2 Avoid Duplicate Serialization in RSC Props
664
+
665
+ **Impact: LOW (reduces network payload by avoiding duplicate serialization)**
666
+
667
+ RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.
668
+
669
+ **Incorrect: duplicates array**
670
+
671
+ ```tsx
672
+ // RSC: sends 6 strings (2 arrays × 3 items)
673
+ <ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
674
+ ```
675
+
676
+ **Correct: sends 3 strings**
677
+
678
+ ```tsx
679
+ // RSC: send once
680
+ <ClientList usernames={usernames} />
681
+
682
+ // Client: transform there
683
+ 'use client'
684
+ const sorted = useMemo(() => [...usernames].sort(), [usernames])
685
+ ```
686
+
687
+ **Nested deduplication behavior:**
688
+
689
+ ```tsx
690
+ // string[] - duplicates everything
691
+ usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
692
+
693
+ // object[] - duplicates array structure only
694
+ users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
695
+ ```
696
+
697
+ Deduplication works recursively. Impact varies by data type:
698
+
699
+ - `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
700
+
701
+ - `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
702
+
703
+ **Operations breaking deduplication: create new references**
704
+
705
+ - Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
706
+
707
+ - Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
708
+
709
+ **More examples:**
710
+
711
+ ```tsx
712
+ // ❌ Bad
713
+ <C users={users} active={users.filter(u => u.active)} />
714
+ <C product={product} productName={product.name} />
715
+
716
+ // ✅ Good
717
+ <C users={users} />
718
+ <C product={product} />
719
+ // Do filtering/destructuring in client
720
+ ```
721
+
722
+ **Exception:** Pass derived data when transformation is expensive or client doesn't need original.
723
+
724
+ ### 3.3 Cross-Request LRU Caching
725
+
726
+ **Impact: HIGH (caches across requests)**
727
+
728
+ `React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
729
+
730
+ **Implementation:**
731
+
732
+ ```typescript
733
+ import { LRUCache } from 'lru-cache'
734
+
735
+ const cache = new LRUCache<string, any>({
736
+ max: 1000,
737
+ ttl: 5 * 60 * 1000 // 5 minutes
738
+ })
739
+
740
+ export async function getUser(id: string) {
741
+ const cached = cache.get(id)
742
+ if (cached) return cached
743
+
744
+ const user = await db.user.findUnique({ where: { id } })
745
+ cache.set(id, user)
746
+ return user
747
+ }
748
+
749
+ // Request 1: DB query, result cached
750
+ // Request 2: cache hit, no DB query
751
+ ```
752
+
753
+ Use when sequential user actions hit multiple endpoints needing the same data within seconds.
754
+
755
+ **With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.
756
+
757
+ **In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
758
+
759
+ Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
760
+
761
+ ### 3.4 Minimize Serialization at RSC Boundaries
762
+
763
+ **Impact: HIGH (reduces data transfer size)**
764
+
765
+ The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.
766
+
767
+ **Incorrect: serializes all 50 fields**
768
+
769
+ ```tsx
770
+ async function Page() {
771
+ const user = await fetchUser() // 50 fields
772
+ return <Profile user={user} />
773
+ }
774
+
775
+ 'use client'
776
+ function Profile({ user }: { user: User }) {
777
+ return <div>{user.name}</div> // uses 1 field
778
+ }
779
+ ```
780
+
781
+ **Correct: serializes only 1 field**
782
+
783
+ ```tsx
784
+ async function Page() {
785
+ const user = await fetchUser()
786
+ return <Profile name={user.name} />
787
+ }
788
+
789
+ 'use client'
790
+ function Profile({ name }: { name: string }) {
791
+ return <div>{name}</div>
792
+ }
793
+ ```
794
+
795
+ ### 3.5 Parallel Data Fetching with Component Composition
796
+
797
+ **Impact: CRITICAL (eliminates server-side waterfalls)**
798
+
799
+ React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
800
+
801
+ **Incorrect: Sidebar waits for Page's fetch to complete**
802
+
803
+ ```tsx
804
+ export default async function Page() {
805
+ const header = await fetchHeader()
806
+ return (
807
+ <div>
808
+ <div>{header}</div>
809
+ <Sidebar />
810
+ </div>
811
+ )
812
+ }
813
+
814
+ async function Sidebar() {
815
+ const items = await fetchSidebarItems()
816
+ return <nav>{items.map(renderItem)}</nav>
817
+ }
818
+ ```
819
+
820
+ **Correct: both fetch simultaneously**
821
+
822
+ ```tsx
823
+ async function Header() {
824
+ const data = await fetchHeader()
825
+ return <div>{data}</div>
826
+ }
827
+
828
+ async function Sidebar() {
829
+ const items = await fetchSidebarItems()
830
+ return <nav>{items.map(renderItem)}</nav>
831
+ }
832
+
833
+ export default function Page() {
834
+ return (
835
+ <div>
836
+ <Header />
837
+ <Sidebar />
838
+ </div>
839
+ )
840
+ }
841
+ ```
842
+
843
+ **Alternative with children prop:**
844
+
845
+ ```tsx
846
+ async function Header() {
847
+ const data = await fetchHeader()
848
+ return <div>{data}</div>
849
+ }
850
+
851
+ async function Sidebar() {
852
+ const items = await fetchSidebarItems()
853
+ return <nav>{items.map(renderItem)}</nav>
854
+ }
855
+
856
+ function Layout({ children }: { children: ReactNode }) {
857
+ return (
858
+ <div>
859
+ <Header />
860
+ {children}
861
+ </div>
862
+ )
863
+ }
864
+
865
+ export default function Page() {
866
+ return (
867
+ <Layout>
868
+ <Sidebar />
869
+ </Layout>
870
+ )
871
+ }
872
+ ```
873
+
874
+ ### 3.6 Per-Request Deduplication with React.cache()
875
+
876
+ **Impact: MEDIUM (deduplicates within request)**
877
+
878
+ Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
879
+
880
+ **Usage:**
881
+
882
+ ```typescript
883
+ import { cache } from 'react'
884
+
885
+ export const getCurrentUser = cache(async () => {
886
+ const session = await auth()
887
+ if (!session?.user?.id) return null
888
+ return await db.user.findUnique({
889
+ where: { id: session.user.id }
890
+ })
891
+ })
892
+ ```
893
+
894
+ Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
895
+
896
+ **Avoid inline objects as arguments:**
897
+
898
+ `React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
899
+
900
+ **Incorrect: always cache miss**
901
+
902
+ ```typescript
903
+ const getUser = cache(async (params: { uid: number }) => {
904
+ return await db.user.findUnique({ where: { id: params.uid } })
905
+ })
906
+
907
+ // Each call creates new object, never hits cache
908
+ getUser({ uid: 1 })
909
+ getUser({ uid: 1 }) // Cache miss, runs query again
910
+ ```
911
+
912
+ **Correct: cache hit**
913
+
914
+ ```typescript
915
+ const params = { uid: 1 }
916
+ getUser(params) // Query runs
917
+ getUser(params) // Cache hit (same reference)
918
+ ```
919
+
920
+ If you must pass objects, pass the same reference:
921
+
922
+ **Next.js-Specific Note:**
923
+
924
+ In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:
925
+
926
+ - Database queries (Prisma, Drizzle, etc.)
927
+
928
+ - Heavy computations
929
+
930
+ - Authentication checks
931
+
932
+ - File system operations
933
+
934
+ - Any non-fetch async work
935
+
936
+ Use `React.cache()` to deduplicate these operations across your component tree.
937
+
938
+ Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)
939
+
940
+ ### 3.7 Use after() for Non-Blocking Operations
941
+
942
+ **Impact: MEDIUM (faster response times)**
943
+
944
+ Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.
945
+
946
+ **Incorrect: blocks response**
947
+
948
+ ```tsx
949
+ import { logUserAction } from '@/app/utils'
950
+
951
+ export async function POST(request: Request) {
952
+ // Perform mutation
953
+ await updateDatabase(request)
954
+
955
+ // Logging blocks the response
956
+ const userAgent = request.headers.get('user-agent') || 'unknown'
957
+ await logUserAction({ userAgent })
958
+
959
+ return new Response(JSON.stringify({ status: 'success' }), {
960
+ status: 200,
961
+ headers: { 'Content-Type': 'application/json' }
962
+ })
963
+ }
964
+ ```
965
+
966
+ **Correct: non-blocking**
967
+
968
+ ```tsx
969
+ import { after } from 'next/server'
970
+ import { headers, cookies } from 'next/headers'
971
+ import { logUserAction } from '@/app/utils'
972
+
973
+ export async function POST(request: Request) {
974
+ // Perform mutation
975
+ await updateDatabase(request)
976
+
977
+ // Log after response is sent
978
+ after(async () => {
979
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
980
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
981
+
982
+ logUserAction({ sessionCookie, userAgent })
983
+ })
984
+
985
+ return new Response(JSON.stringify({ status: 'success' }), {
986
+ status: 200,
987
+ headers: { 'Content-Type': 'application/json' }
988
+ })
989
+ }
990
+ ```
991
+
992
+ The response is sent immediately while logging happens in the background.
993
+
994
+ **Common use cases:**
995
+
996
+ - Analytics tracking
997
+
998
+ - Audit logging
999
+
1000
+ - Sending notifications
1001
+
1002
+ - Cache invalidation
1003
+
1004
+ - Cleanup tasks
1005
+
1006
+ **Important notes:**
1007
+
1008
+ - `after()` runs even if the response fails or redirects
1009
+
1010
+ - Works in Server Actions, Route Handlers, and Server Components
1011
+
1012
+ Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
1013
+
1014
+ ---
1015
+
1016
+ ## 4. Client-Side Data Fetching
1017
+
1018
+ **Impact: MEDIUM-HIGH**
1019
+
1020
+ Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
1021
+
1022
+ ### 4.1 Deduplicate Global Event Listeners
1023
+
1024
+ **Impact: LOW (single listener for N components)**
1025
+
1026
+ Use `useSWRSubscription()` to share global event listeners across component instances.
1027
+
1028
+ **Incorrect: N instances = N listeners**
1029
+
1030
+ ```tsx
1031
+ function useKeyboardShortcut(key: string, callback: () => void) {
1032
+ useEffect(() => {
1033
+ const handler = (e: KeyboardEvent) => {
1034
+ if (e.metaKey && e.key === key) {
1035
+ callback()
1036
+ }
1037
+ }
1038
+ window.addEventListener('keydown', handler)
1039
+ return () => window.removeEventListener('keydown', handler)
1040
+ }, [key, callback])
1041
+ }
1042
+ ```
1043
+
1044
+ When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
1045
+
1046
+ **Correct: N instances = 1 listener**
1047
+
1048
+ ```tsx
1049
+ import useSWRSubscription from 'swr/subscription'
1050
+
1051
+ // Module-level Map to track callbacks per key
1052
+ const keyCallbacks = new Map<string, Set<() => void>>()
1053
+
1054
+ function useKeyboardShortcut(key: string, callback: () => void) {
1055
+ // Register this callback in the Map
1056
+ useEffect(() => {
1057
+ if (!keyCallbacks.has(key)) {
1058
+ keyCallbacks.set(key, new Set())
1059
+ }
1060
+ keyCallbacks.get(key)!.add(callback)
1061
+
1062
+ return () => {
1063
+ const set = keyCallbacks.get(key)
1064
+ if (set) {
1065
+ set.delete(callback)
1066
+ if (set.size === 0) {
1067
+ keyCallbacks.delete(key)
1068
+ }
1069
+ }
1070
+ }
1071
+ }, [key, callback])
1072
+
1073
+ useSWRSubscription('global-keydown', () => {
1074
+ const handler = (e: KeyboardEvent) => {
1075
+ if (e.metaKey && keyCallbacks.has(e.key)) {
1076
+ keyCallbacks.get(e.key)!.forEach(cb => cb())
1077
+ }
1078
+ }
1079
+ window.addEventListener('keydown', handler)
1080
+ return () => window.removeEventListener('keydown', handler)
1081
+ })
1082
+ }
1083
+
1084
+ function Profile() {
1085
+ // Multiple shortcuts will share the same listener
1086
+ useKeyboardShortcut('p', () => { /* ... */ })
1087
+ useKeyboardShortcut('k', () => { /* ... */ })
1088
+ // ...
1089
+ }
1090
+ ```
1091
+
1092
+ ### 4.2 Use Passive Event Listeners for Scrolling Performance
1093
+
1094
+ **Impact: MEDIUM (eliminates scroll delay caused by event listeners)**
1095
+
1096
+ Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
1097
+
1098
+ **Incorrect:**
1099
+
1100
+ ```typescript
1101
+ useEffect(() => {
1102
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
1103
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
1104
+
1105
+ document.addEventListener('touchstart', handleTouch)
1106
+ document.addEventListener('wheel', handleWheel)
1107
+
1108
+ return () => {
1109
+ document.removeEventListener('touchstart', handleTouch)
1110
+ document.removeEventListener('wheel', handleWheel)
1111
+ }
1112
+ }, [])
1113
+ ```
1114
+
1115
+ **Correct:**
1116
+
1117
+ ```typescript
1118
+ useEffect(() => {
1119
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
1120
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
1121
+
1122
+ document.addEventListener('touchstart', handleTouch, { passive: true })
1123
+ document.addEventListener('wheel', handleWheel, { passive: true })
1124
+
1125
+ return () => {
1126
+ document.removeEventListener('touchstart', handleTouch)
1127
+ document.removeEventListener('wheel', handleWheel)
1128
+ }
1129
+ }, [])
1130
+ ```
1131
+
1132
+ **Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
1133
+
1134
+ **Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
1135
+
1136
+ ### 4.3 Use SWR for Automatic Deduplication
1137
+
1138
+ **Impact: MEDIUM-HIGH (automatic deduplication)**
1139
+
1140
+ SWR enables request deduplication, caching, and revalidation across component instances.
1141
+
1142
+ **Incorrect: no deduplication, each instance fetches**
1143
+
1144
+ ```tsx
1145
+ function UserList() {
1146
+ const [users, setUsers] = useState([])
1147
+ useEffect(() => {
1148
+ fetch('/api/users')
1149
+ .then(r => r.json())
1150
+ .then(setUsers)
1151
+ }, [])
1152
+ }
1153
+ ```
1154
+
1155
+ **Correct: multiple instances share one request**
1156
+
1157
+ ```tsx
1158
+ import useSWR from 'swr'
1159
+
1160
+ function UserList() {
1161
+ const { data: users } = useSWR('/api/users', fetcher)
1162
+ }
1163
+ ```
1164
+
1165
+ **For immutable data:**
1166
+
1167
+ ```tsx
1168
+ import { useImmutableSWR } from '@/lib/swr'
1169
+
1170
+ function StaticContent() {
1171
+ const { data } = useImmutableSWR('/api/config', fetcher)
1172
+ }
1173
+ ```
1174
+
1175
+ **For mutations:**
1176
+
1177
+ ```tsx
1178
+ import { useSWRMutation } from 'swr/mutation'
1179
+
1180
+ function UpdateButton() {
1181
+ const { trigger } = useSWRMutation('/api/user', updateUser)
1182
+ return <button onClick={() => trigger()}>Update</button>
1183
+ }
1184
+ ```
1185
+
1186
+ Reference: [https://swr.vercel.app](https://swr.vercel.app)
1187
+
1188
+ ### 4.4 Version and Minimize localStorage Data
1189
+
1190
+ **Impact: MEDIUM (prevents schema conflicts, reduces storage size)**
1191
+
1192
+ Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
1193
+
1194
+ **Incorrect:**
1195
+
1196
+ ```typescript
1197
+ // No version, stores everything, no error handling
1198
+ localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
1199
+ const data = localStorage.getItem('userConfig')
1200
+ ```
1201
+
1202
+ **Correct:**
1203
+
1204
+ ```typescript
1205
+ const VERSION = 'v2'
1206
+
1207
+ function saveConfig(config: { theme: string; language: string }) {
1208
+ try {
1209
+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
1210
+ } catch {
1211
+ // Throws in incognito/private browsing, quota exceeded, or disabled
1212
+ }
1213
+ }
1214
+
1215
+ function loadConfig() {
1216
+ try {
1217
+ const data = localStorage.getItem(`userConfig:${VERSION}`)
1218
+ return data ? JSON.parse(data) : null
1219
+ } catch {
1220
+ return null
1221
+ }
1222
+ }
1223
+
1224
+ // Migration from v1 to v2
1225
+ function migrate() {
1226
+ try {
1227
+ const v1 = localStorage.getItem('userConfig:v1')
1228
+ if (v1) {
1229
+ const old = JSON.parse(v1)
1230
+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
1231
+ localStorage.removeItem('userConfig:v1')
1232
+ }
1233
+ } catch {}
1234
+ }
1235
+ ```
1236
+
1237
+ **Store minimal fields from server responses:**
1238
+
1239
+ ```typescript
1240
+ // User object has 20+ fields, only store what UI needs
1241
+ function cachePrefs(user: FullUser) {
1242
+ try {
1243
+ localStorage.setItem('prefs:v1', JSON.stringify({
1244
+ theme: user.preferences.theme,
1245
+ notifications: user.preferences.notifications
1246
+ }))
1247
+ } catch {}
1248
+ }
1249
+ ```
1250
+
1251
+ **Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
1252
+
1253
+ **Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
1254
+
1255
+ ---
1256
+
1257
+ ## 5. Re-render Optimization
1258
+
1259
+ **Impact: MEDIUM**
1260
+
1261
+ Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
1262
+
1263
+ ### 5.1 Defer State Reads to Usage Point
1264
+
1265
+ **Impact: MEDIUM (avoids unnecessary subscriptions)**
1266
+
1267
+ Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
1268
+
1269
+ **Incorrect: subscribes to all searchParams changes**
1270
+
1271
+ ```tsx
1272
+ function ShareButton({ chatId }: { chatId: string }) {
1273
+ const searchParams = useSearchParams()
1274
+
1275
+ const handleShare = () => {
1276
+ const ref = searchParams.get('ref')
1277
+ shareChat(chatId, { ref })
1278
+ }
1279
+
1280
+ return <button onClick={handleShare}>Share</button>
1281
+ }
1282
+ ```
1283
+
1284
+ **Correct: reads on demand, no subscription**
1285
+
1286
+ ```tsx
1287
+ function ShareButton({ chatId }: { chatId: string }) {
1288
+ const handleShare = () => {
1289
+ const params = new URLSearchParams(window.location.search)
1290
+ const ref = params.get('ref')
1291
+ shareChat(chatId, { ref })
1292
+ }
1293
+
1294
+ return <button onClick={handleShare}>Share</button>
1295
+ }
1296
+ ```
1297
+
1298
+ ### 5.2 Extract to Memoized Components
1299
+
1300
+ **Impact: MEDIUM (enables early returns)**
1301
+
1302
+ Extract expensive work into memoized components to enable early returns before computation.
1303
+
1304
+ **Incorrect: computes avatar even when loading**
1305
+
1306
+ ```tsx
1307
+ function Profile({ user, loading }: Props) {
1308
+ const avatar = useMemo(() => {
1309
+ const id = computeAvatarId(user)
1310
+ return <Avatar id={id} />
1311
+ }, [user])
1312
+
1313
+ if (loading) return <Skeleton />
1314
+ return <div>{avatar}</div>
1315
+ }
1316
+ ```
1317
+
1318
+ **Correct: skips computation when loading**
1319
+
1320
+ ```tsx
1321
+ const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
1322
+ const id = useMemo(() => computeAvatarId(user), [user])
1323
+ return <Avatar id={id} />
1324
+ })
1325
+
1326
+ function Profile({ user, loading }: Props) {
1327
+ if (loading) return <Skeleton />
1328
+ return (
1329
+ <div>
1330
+ <UserAvatar user={user} />
1331
+ </div>
1332
+ )
1333
+ }
1334
+ ```
1335
+
1336
+ **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.
1337
+
1338
+ ### 5.3 Narrow Effect Dependencies
1339
+
1340
+ **Impact: LOW (minimizes effect re-runs)**
1341
+
1342
+ Specify primitive dependencies instead of objects to minimize effect re-runs.
1343
+
1344
+ **Incorrect: re-runs on any user field change**
1345
+
1346
+ ```tsx
1347
+ useEffect(() => {
1348
+ console.log(user.id)
1349
+ }, [user])
1350
+ ```
1351
+
1352
+ **Correct: re-runs only when id changes**
1353
+
1354
+ ```tsx
1355
+ useEffect(() => {
1356
+ console.log(user.id)
1357
+ }, [user.id])
1358
+ ```
1359
+
1360
+ **For derived state, compute outside effect:**
1361
+
1362
+ ```tsx
1363
+ // Incorrect: runs on width=767, 766, 765...
1364
+ useEffect(() => {
1365
+ if (width < 768) {
1366
+ enableMobileMode()
1367
+ }
1368
+ }, [width])
1369
+
1370
+ // Correct: runs only on boolean transition
1371
+ const isMobile = width < 768
1372
+ useEffect(() => {
1373
+ if (isMobile) {
1374
+ enableMobileMode()
1375
+ }
1376
+ }, [isMobile])
1377
+ ```
1378
+
1379
+ ### 5.4 Subscribe to Derived State
1380
+
1381
+ **Impact: MEDIUM (reduces re-render frequency)**
1382
+
1383
+ Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
1384
+
1385
+ **Incorrect: re-renders on every pixel change**
1386
+
1387
+ ```tsx
1388
+ function Sidebar() {
1389
+ const width = useWindowWidth() // updates continuously
1390
+ const isMobile = width < 768
1391
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
1392
+ }
1393
+ ```
1394
+
1395
+ **Correct: re-renders only when boolean changes**
1396
+
1397
+ ```tsx
1398
+ function Sidebar() {
1399
+ const isMobile = useMediaQuery('(max-width: 767px)')
1400
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
1401
+ }
1402
+ ```
1403
+
1404
+ ### 5.5 Use Functional setState Updates
1405
+
1406
+ **Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**
1407
+
1408
+ When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
1409
+
1410
+ **Incorrect: requires state as dependency**
1411
+
1412
+ ```tsx
1413
+ function TodoList() {
1414
+ const [items, setItems] = useState(initialItems)
1415
+
1416
+ // Callback must depend on items, recreated on every items change
1417
+ const addItems = useCallback((newItems: Item[]) => {
1418
+ setItems([...items, ...newItems])
1419
+ }, [items]) // ❌ items dependency causes recreations
1420
+
1421
+ // Risk of stale closure if dependency is forgotten
1422
+ const removeItem = useCallback((id: string) => {
1423
+ setItems(items.filter(item => item.id !== id))
1424
+ }, []) // ❌ Missing items dependency - will use stale items!
1425
+
1426
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
1427
+ }
1428
+ ```
1429
+
1430
+ The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
1431
+
1432
+ **Correct: stable callbacks, no stale closures**
1433
+
1434
+ ```tsx
1435
+ function TodoList() {
1436
+ const [items, setItems] = useState(initialItems)
1437
+
1438
+ // Stable callback, never recreated
1439
+ const addItems = useCallback((newItems: Item[]) => {
1440
+ setItems(curr => [...curr, ...newItems])
1441
+ }, []) // ✅ No dependencies needed
1442
+
1443
+ // Always uses latest state, no stale closure risk
1444
+ const removeItem = useCallback((id: string) => {
1445
+ setItems(curr => curr.filter(item => item.id !== id))
1446
+ }, []) // ✅ Safe and stable
1447
+
1448
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
1449
+ }
1450
+ ```
1451
+
1452
+ **Benefits:**
1453
+
1454
+ 1. **Stable callback references** - Callbacks don't need to be recreated when state changes
1455
+
1456
+ 2. **No stale closures** - Always operates on the latest state value
1457
+
1458
+ 3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
1459
+
1460
+ 4. **Prevents bugs** - Eliminates the most common source of React closure bugs
1461
+
1462
+ **When to use functional updates:**
1463
+
1464
+ - Any setState that depends on the current state value
1465
+
1466
+ - Inside useCallback/useMemo when state is needed
1467
+
1468
+ - Event handlers that reference state
1469
+
1470
+ - Async operations that update state
1471
+
1472
+ **When direct updates are fine:**
1473
+
1474
+ - Setting state to a static value: `setCount(0)`
1475
+
1476
+ - Setting state from props/arguments only: `setName(newName)`
1477
+
1478
+ - State doesn't depend on previous value
1479
+
1480
+ **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
1481
+
1482
+ ### 5.6 Use Lazy State Initialization
1483
+
1484
+ **Impact: MEDIUM (wasted computation on every render)**
1485
+
1486
+ Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
1487
+
1488
+ **Incorrect: runs on every render**
1489
+
1490
+ ```tsx
1491
+ function FilteredList({ items }: { items: Item[] }) {
1492
+ // buildSearchIndex() runs on EVERY render, even after initialization
1493
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
1494
+ const [query, setQuery] = useState('')
1495
+
1496
+ // When query changes, buildSearchIndex runs again unnecessarily
1497
+ return <SearchResults index={searchIndex} query={query} />
1498
+ }
1499
+
1500
+ function UserProfile() {
1501
+ // JSON.parse runs on every render
1502
+ const [settings, setSettings] = useState(
1503
+ JSON.parse(localStorage.getItem('settings') || '{}')
1504
+ )
1505
+
1506
+ return <SettingsForm settings={settings} onChange={setSettings} />
1507
+ }
1508
+ ```
1509
+
1510
+ **Correct: runs only once**
1511
+
1512
+ ```tsx
1513
+ function FilteredList({ items }: { items: Item[] }) {
1514
+ // buildSearchIndex() runs ONLY on initial render
1515
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
1516
+ const [query, setQuery] = useState('')
1517
+
1518
+ return <SearchResults index={searchIndex} query={query} />
1519
+ }
1520
+
1521
+ function UserProfile() {
1522
+ // JSON.parse runs only on initial render
1523
+ const [settings, setSettings] = useState(() => {
1524
+ const stored = localStorage.getItem('settings')
1525
+ return stored ? JSON.parse(stored) : {}
1526
+ })
1527
+
1528
+ return <SettingsForm settings={settings} onChange={setSettings} />
1529
+ }
1530
+ ```
1531
+
1532
+ Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
1533
+
1534
+ For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
1535
+
1536
+ ### 5.7 Use Transitions for Non-Urgent Updates
1537
+
1538
+ **Impact: MEDIUM (maintains UI responsiveness)**
1539
+
1540
+ Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
1541
+
1542
+ **Incorrect: blocks UI on every scroll**
1543
+
1544
+ ```tsx
1545
+ function ScrollTracker() {
1546
+ const [scrollY, setScrollY] = useState(0)
1547
+ useEffect(() => {
1548
+ const handler = () => setScrollY(window.scrollY)
1549
+ window.addEventListener('scroll', handler, { passive: true })
1550
+ return () => window.removeEventListener('scroll', handler)
1551
+ }, [])
1552
+ }
1553
+ ```
1554
+
1555
+ **Correct: non-blocking updates**
1556
+
1557
+ ```tsx
1558
+ import { startTransition } from 'react'
1559
+
1560
+ function ScrollTracker() {
1561
+ const [scrollY, setScrollY] = useState(0)
1562
+ useEffect(() => {
1563
+ const handler = () => {
1564
+ startTransition(() => setScrollY(window.scrollY))
1565
+ }
1566
+ window.addEventListener('scroll', handler, { passive: true })
1567
+ return () => window.removeEventListener('scroll', handler)
1568
+ }, [])
1569
+ }
1570
+ ```
1571
+
1572
+ ---
1573
+
1574
+ ## 6. Rendering Performance
1575
+
1576
+ **Impact: MEDIUM**
1577
+
1578
+ Optimizing the rendering process reduces the work the browser needs to do.
1579
+
1580
+ ### 6.1 Animate SVG Wrapper Instead of SVG Element
1581
+
1582
+ **Impact: LOW (enables hardware acceleration)**
1583
+
1584
+ Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
1585
+
1586
+ **Incorrect: animating SVG directly - no hardware acceleration**
1587
+
1588
+ ```tsx
1589
+ function LoadingSpinner() {
1590
+ return (
1591
+ <svg
1592
+ className="animate-spin"
1593
+ width="24"
1594
+ height="24"
1595
+ viewBox="0 0 24 24"
1596
+ >
1597
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
1598
+ </svg>
1599
+ )
1600
+ }
1601
+ ```
1602
+
1603
+ **Correct: animating wrapper div - hardware accelerated**
1604
+
1605
+ ```tsx
1606
+ function LoadingSpinner() {
1607
+ return (
1608
+ <div className="animate-spin">
1609
+ <svg
1610
+ width="24"
1611
+ height="24"
1612
+ viewBox="0 0 24 24"
1613
+ >
1614
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
1615
+ </svg>
1616
+ </div>
1617
+ )
1618
+ }
1619
+ ```
1620
+
1621
+ This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
1622
+
1623
+ ### 6.2 CSS content-visibility for Long Lists
1624
+
1625
+ **Impact: HIGH (faster initial render)**
1626
+
1627
+ Apply `content-visibility: auto` to defer off-screen rendering.
1628
+
1629
+ **CSS:**
1630
+
1631
+ ```css
1632
+ .message-item {
1633
+ content-visibility: auto;
1634
+ contain-intrinsic-size: 0 80px;
1635
+ }
1636
+ ```
1637
+
1638
+ **Example:**
1639
+
1640
+ ```tsx
1641
+ function MessageList({ messages }: { messages: Message[] }) {
1642
+ return (
1643
+ <div className="overflow-y-auto h-screen">
1644
+ {messages.map(msg => (
1645
+ <div key={msg.id} className="message-item">
1646
+ <Avatar user={msg.author} />
1647
+ <div>{msg.content}</div>
1648
+ </div>
1649
+ ))}
1650
+ </div>
1651
+ )
1652
+ }
1653
+ ```
1654
+
1655
+ For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
1656
+
1657
+ ### 6.3 Hoist Static JSX Elements
1658
+
1659
+ **Impact: LOW (avoids re-creation)**
1660
+
1661
+ Extract static JSX outside components to avoid re-creation.
1662
+
1663
+ **Incorrect: recreates element every render**
1664
+
1665
+ ```tsx
1666
+ function LoadingSkeleton() {
1667
+ return <div className="animate-pulse h-20 bg-gray-200" />
1668
+ }
1669
+
1670
+ function Container() {
1671
+ return (
1672
+ <div>
1673
+ {loading && <LoadingSkeleton />}
1674
+ </div>
1675
+ )
1676
+ }
1677
+ ```
1678
+
1679
+ **Correct: reuses same element**
1680
+
1681
+ ```tsx
1682
+ const loadingSkeleton = (
1683
+ <div className="animate-pulse h-20 bg-gray-200" />
1684
+ )
1685
+
1686
+ function Container() {
1687
+ return (
1688
+ <div>
1689
+ {loading && loadingSkeleton}
1690
+ </div>
1691
+ )
1692
+ }
1693
+ ```
1694
+
1695
+ This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
1696
+
1697
+ **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
1698
+
1699
+ ### 6.4 Optimize SVG Precision
1700
+
1701
+ **Impact: LOW (reduces file size)**
1702
+
1703
+ Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
1704
+
1705
+ **Incorrect: excessive precision**
1706
+
1707
+ ```svg
1708
+ <path d="M 10.293847 20.847362 L 30.938472 40.192837" />
1709
+ ```
1710
+
1711
+ **Correct: 1 decimal place**
1712
+
1713
+ ```svg
1714
+ <path d="M 10.3 20.8 L 30.9 40.2" />
1715
+ ```
1716
+
1717
+ **Automate with SVGO:**
1718
+
1719
+ ```bash
1720
+ npx svgo --precision=1 --multipass icon.svg
1721
+ ```
1722
+
1723
+ ### 6.5 Prevent Hydration Mismatch Without Flickering
1724
+
1725
+ **Impact: MEDIUM (avoids visual flicker and hydration errors)**
1726
+
1727
+ When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
1728
+
1729
+ **Incorrect: breaks SSR**
1730
+
1731
+ ```tsx
1732
+ function ThemeWrapper({ children }: { children: ReactNode }) {
1733
+ // localStorage is not available on server - throws error
1734
+ const theme = localStorage.getItem('theme') || 'light'
1735
+
1736
+ return (
1737
+ <div className={theme}>
1738
+ {children}
1739
+ </div>
1740
+ )
1741
+ }
1742
+ ```
1743
+
1744
+ Server-side rendering will fail because `localStorage` is undefined.
1745
+
1746
+ **Incorrect: visual flickering**
1747
+
1748
+ ```tsx
1749
+ function ThemeWrapper({ children }: { children: ReactNode }) {
1750
+ const [theme, setTheme] = useState('light')
1751
+
1752
+ useEffect(() => {
1753
+ // Runs after hydration - causes visible flash
1754
+ const stored = localStorage.getItem('theme')
1755
+ if (stored) {
1756
+ setTheme(stored)
1757
+ }
1758
+ }, [])
1759
+
1760
+ return (
1761
+ <div className={theme}>
1762
+ {children}
1763
+ </div>
1764
+ )
1765
+ }
1766
+ ```
1767
+
1768
+ Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
1769
+
1770
+ **Correct: no flicker, no hydration mismatch**
1771
+
1772
+ ```tsx
1773
+ function ThemeWrapper({ children }: { children: ReactNode }) {
1774
+ return (
1775
+ <>
1776
+ <div id="theme-wrapper">
1777
+ {children}
1778
+ </div>
1779
+ <script
1780
+ dangerouslySetInnerHTML={{
1781
+ __html: `
1782
+ (function() {
1783
+ try {
1784
+ var theme = localStorage.getItem('theme') || 'light';
1785
+ var el = document.getElementById('theme-wrapper');
1786
+ if (el) el.className = theme;
1787
+ } catch (e) {}
1788
+ })();
1789
+ `,
1790
+ }}
1791
+ />
1792
+ </>
1793
+ )
1794
+ }
1795
+ ```
1796
+
1797
+ The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
1798
+
1799
+ This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
1800
+
1801
+ ### 6.6 Use Activity Component for Show/Hide
1802
+
1803
+ **Impact: MEDIUM (preserves state/DOM)**
1804
+
1805
+ Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
1806
+
1807
+ **Usage:**
1808
+
1809
+ ```tsx
1810
+ import { Activity } from 'react'
1811
+
1812
+ function Dropdown({ isOpen }: Props) {
1813
+ return (
1814
+ <Activity mode={isOpen ? 'visible' : 'hidden'}>
1815
+ <ExpensiveMenu />
1816
+ </Activity>
1817
+ )
1818
+ }
1819
+ ```
1820
+
1821
+ Avoids expensive re-renders and state loss.
1822
+
1823
+ ### 6.7 Use Explicit Conditional Rendering
1824
+
1825
+ **Impact: LOW (prevents rendering 0 or NaN)**
1826
+
1827
+ Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
1828
+
1829
+ **Incorrect: renders "0" when count is 0**
1830
+
1831
+ ```tsx
1832
+ function Badge({ count }: { count: number }) {
1833
+ return (
1834
+ <div>
1835
+ {count && <span className="badge">{count}</span>}
1836
+ </div>
1837
+ )
1838
+ }
1839
+
1840
+ // When count = 0, renders: <div>0</div>
1841
+ // When count = 5, renders: <div><span class="badge">5</span></div>
1842
+ ```
1843
+
1844
+ **Correct: renders nothing when count is 0**
1845
+
1846
+ ```tsx
1847
+ function Badge({ count }: { count: number }) {
1848
+ return (
1849
+ <div>
1850
+ {count > 0 ? <span className="badge">{count}</span> : null}
1851
+ </div>
1852
+ )
1853
+ }
1854
+
1855
+ // When count = 0, renders: <div></div>
1856
+ // When count = 5, renders: <div><span class="badge">5</span></div>
1857
+ ```
1858
+
1859
+ ---
1860
+
1861
+ ## 7. JavaScript Performance
1862
+
1863
+ **Impact: LOW-MEDIUM**
1864
+
1865
+ Micro-optimizations for hot paths can add up to meaningful improvements.
1866
+
1867
+ ### 7.1 Batch DOM CSS Changes
1868
+
1869
+ **Impact: MEDIUM (reduces reflows/repaints)**
1870
+
1871
+ Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
1872
+
1873
+ **Incorrect: interleaved reads and writes force reflows**
1874
+
1875
+ ```typescript
1876
+ function updateElementStyles(element: HTMLElement) {
1877
+ element.style.width = '100px'
1878
+ const width = element.offsetWidth // Forces reflow
1879
+ element.style.height = '200px'
1880
+ const height = element.offsetHeight // Forces another reflow
1881
+ }
1882
+ ```
1883
+
1884
+ **Correct: batch writes, then read once**
1885
+
1886
+ ```typescript
1887
+ function updateElementStyles(element: HTMLElement) {
1888
+ element.classList.add('highlighted-box')
1889
+
1890
+ const { width, height } = element.getBoundingClientRect()
1891
+ }
1892
+ ```
1893
+
1894
+ **Better: use CSS classes**
1895
+
1896
+ Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
1897
+
1898
+ ### 7.2 Build Index Maps for Repeated Lookups
1899
+
1900
+ **Impact: LOW-MEDIUM (1M ops to 2K ops)**
1901
+
1902
+ Multiple `.find()` calls by the same key should use a Map.
1903
+
1904
+ **Incorrect (O(n) per lookup):**
1905
+
1906
+ ```typescript
1907
+ function processOrders(orders: Order[], users: User[]) {
1908
+ return orders.map(order => ({
1909
+ ...order,
1910
+ user: users.find(u => u.id === order.userId)
1911
+ }))
1912
+ }
1913
+ ```
1914
+
1915
+ **Correct (O(1) per lookup):**
1916
+
1917
+ ```typescript
1918
+ function processOrders(orders: Order[], users: User[]) {
1919
+ const userById = new Map(users.map(u => [u.id, u]))
1920
+
1921
+ return orders.map(order => ({
1922
+ ...order,
1923
+ user: userById.get(order.userId)
1924
+ }))
1925
+ }
1926
+ ```
1927
+
1928
+ Build map once (O(n)), then all lookups are O(1).
1929
+
1930
+ For 1000 orders × 1000 users: 1M ops → 2K ops.
1931
+
1932
+ ### 7.3 Cache Property Access in Loops
1933
+
1934
+ **Impact: LOW-MEDIUM (reduces lookups)**
1935
+
1936
+ Cache object property lookups in hot paths.
1937
+
1938
+ **Incorrect: 3 lookups × N iterations**
1939
+
1940
+ ```typescript
1941
+ for (let i = 0; i < arr.length; i++) {
1942
+ process(obj.config.settings.value)
1943
+ }
1944
+ ```
1945
+
1946
+ **Correct: 1 lookup total**
1947
+
1948
+ ```typescript
1949
+ const value = obj.config.settings.value
1950
+ const len = arr.length
1951
+ for (let i = 0; i < len; i++) {
1952
+ process(value)
1953
+ }
1954
+ ```
1955
+
1956
+ ### 7.4 Cache Repeated Function Calls
1957
+
1958
+ **Impact: MEDIUM (avoid redundant computation)**
1959
+
1960
+ Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
1961
+
1962
+ **Incorrect: redundant computation**
1963
+
1964
+ ```typescript
1965
+ function ProjectList({ projects }: { projects: Project[] }) {
1966
+ return (
1967
+ <div>
1968
+ {projects.map(project => {
1969
+ // slugify() called 100+ times for same project names
1970
+ const slug = slugify(project.name)
1971
+
1972
+ return <ProjectCard key={project.id} slug={slug} />
1973
+ })}
1974
+ </div>
1975
+ )
1976
+ }
1977
+ ```
1978
+
1979
+ **Correct: cached results**
1980
+
1981
+ ```typescript
1982
+ // Module-level cache
1983
+ const slugifyCache = new Map<string, string>()
1984
+
1985
+ function cachedSlugify(text: string): string {
1986
+ if (slugifyCache.has(text)) {
1987
+ return slugifyCache.get(text)!
1988
+ }
1989
+ const result = slugify(text)
1990
+ slugifyCache.set(text, result)
1991
+ return result
1992
+ }
1993
+
1994
+ function ProjectList({ projects }: { projects: Project[] }) {
1995
+ return (
1996
+ <div>
1997
+ {projects.map(project => {
1998
+ // Computed only once per unique project name
1999
+ const slug = cachedSlugify(project.name)
2000
+
2001
+ return <ProjectCard key={project.id} slug={slug} />
2002
+ })}
2003
+ </div>
2004
+ )
2005
+ }
2006
+ ```
2007
+
2008
+ **Simpler pattern for single-value functions:**
2009
+
2010
+ ```typescript
2011
+ let isLoggedInCache: boolean | null = null
2012
+
2013
+ function isLoggedIn(): boolean {
2014
+ if (isLoggedInCache !== null) {
2015
+ return isLoggedInCache
2016
+ }
2017
+
2018
+ isLoggedInCache = document.cookie.includes('auth=')
2019
+ return isLoggedInCache
2020
+ }
2021
+
2022
+ // Clear cache when auth changes
2023
+ function onAuthChange() {
2024
+ isLoggedInCache = null
2025
+ }
2026
+ ```
2027
+
2028
+ Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
2029
+
2030
+ Reference: [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
2031
+
2032
+ ### 7.5 Cache Storage API Calls
2033
+
2034
+ **Impact: LOW-MEDIUM (reduces expensive I/O)**
2035
+
2036
+ `localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
2037
+
2038
+ **Incorrect: reads storage on every call**
2039
+
2040
+ ```typescript
2041
+ function getTheme() {
2042
+ return localStorage.getItem('theme') ?? 'light'
2043
+ }
2044
+ // Called 10 times = 10 storage reads
2045
+ ```
2046
+
2047
+ **Correct: Map cache**
2048
+
2049
+ ```typescript
2050
+ const storageCache = new Map<string, string | null>()
2051
+
2052
+ function getLocalStorage(key: string) {
2053
+ if (!storageCache.has(key)) {
2054
+ storageCache.set(key, localStorage.getItem(key))
2055
+ }
2056
+ return storageCache.get(key)
2057
+ }
2058
+
2059
+ function setLocalStorage(key: string, value: string) {
2060
+ localStorage.setItem(key, value)
2061
+ storageCache.set(key, value) // keep cache in sync
2062
+ }
2063
+ ```
2064
+
2065
+ Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
2066
+
2067
+ **Cookie caching:**
2068
+
2069
+ ```typescript
2070
+ let cookieCache: Record<string, string> | null = null
2071
+
2072
+ function getCookie(name: string) {
2073
+ if (!cookieCache) {
2074
+ cookieCache = Object.fromEntries(
2075
+ document.cookie.split('; ').map(c => c.split('='))
2076
+ )
2077
+ }
2078
+ return cookieCache[name]
2079
+ }
2080
+ ```
2081
+
2082
+ **Important: invalidate on external changes**
2083
+
2084
+ ```typescript
2085
+ window.addEventListener('storage', (e) => {
2086
+ if (e.key) storageCache.delete(e.key)
2087
+ })
2088
+
2089
+ document.addEventListener('visibilitychange', () => {
2090
+ if (document.visibilityState === 'visible') {
2091
+ storageCache.clear()
2092
+ }
2093
+ })
2094
+ ```
2095
+
2096
+ If storage can change externally (another tab, server-set cookies), invalidate cache:
2097
+
2098
+ ### 7.6 Combine Multiple Array Iterations
2099
+
2100
+ **Impact: LOW-MEDIUM (reduces iterations)**
2101
+
2102
+ Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
2103
+
2104
+ **Incorrect: 3 iterations**
2105
+
2106
+ ```typescript
2107
+ const admins = users.filter(u => u.isAdmin)
2108
+ const testers = users.filter(u => u.isTester)
2109
+ const inactive = users.filter(u => !u.isActive)
2110
+ ```
2111
+
2112
+ **Correct: 1 iteration**
2113
+
2114
+ ```typescript
2115
+ const admins: User[] = []
2116
+ const testers: User[] = []
2117
+ const inactive: User[] = []
2118
+
2119
+ for (const user of users) {
2120
+ if (user.isAdmin) admins.push(user)
2121
+ if (user.isTester) testers.push(user)
2122
+ if (!user.isActive) inactive.push(user)
2123
+ }
2124
+ ```
2125
+
2126
+ ### 7.7 Early Length Check for Array Comparisons
2127
+
2128
+ **Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**
2129
+
2130
+ When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
2131
+
2132
+ In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
2133
+
2134
+ **Incorrect: always runs expensive comparison**
2135
+
2136
+ ```typescript
2137
+ function hasChanges(current: string[], original: string[]) {
2138
+ // Always sorts and joins, even when lengths differ
2139
+ return current.sort().join() !== original.sort().join()
2140
+ }
2141
+ ```
2142
+
2143
+ Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
2144
+
2145
+ **Correct (O(1) length check first):**
2146
+
2147
+ ```typescript
2148
+ function hasChanges(current: string[], original: string[]) {
2149
+ // Early return if lengths differ
2150
+ if (current.length !== original.length) {
2151
+ return true
2152
+ }
2153
+ // Only sort when lengths match
2154
+ const currentSorted = current.toSorted()
2155
+ const originalSorted = original.toSorted()
2156
+ for (let i = 0; i < currentSorted.length; i++) {
2157
+ if (currentSorted[i] !== originalSorted[i]) {
2158
+ return true
2159
+ }
2160
+ }
2161
+ return false
2162
+ }
2163
+ ```
2164
+
2165
+ This new approach is more efficient because:
2166
+
2167
+ - It avoids the overhead of sorting and joining the arrays when lengths differ
2168
+
2169
+ - It avoids consuming memory for the joined strings (especially important for large arrays)
2170
+
2171
+ - It avoids mutating the original arrays
2172
+
2173
+ - It returns early when a difference is found
2174
+
2175
+ ### 7.8 Early Return from Functions
2176
+
2177
+ **Impact: LOW-MEDIUM (avoids unnecessary computation)**
2178
+
2179
+ Return early when result is determined to skip unnecessary processing.
2180
+
2181
+ **Incorrect: processes all items even after finding answer**
2182
+
2183
+ ```typescript
2184
+ function validateUsers(users: User[]) {
2185
+ let hasError = false
2186
+ let errorMessage = ''
2187
+
2188
+ for (const user of users) {
2189
+ if (!user.email) {
2190
+ hasError = true
2191
+ errorMessage = 'Email required'
2192
+ }
2193
+ if (!user.name) {
2194
+ hasError = true
2195
+ errorMessage = 'Name required'
2196
+ }
2197
+ // Continues checking all users even after error found
2198
+ }
2199
+
2200
+ return hasError ? { valid: false, error: errorMessage } : { valid: true }
2201
+ }
2202
+ ```
2203
+
2204
+ **Correct: returns immediately on first error**
2205
+
2206
+ ```typescript
2207
+ function validateUsers(users: User[]) {
2208
+ for (const user of users) {
2209
+ if (!user.email) {
2210
+ return { valid: false, error: 'Email required' }
2211
+ }
2212
+ if (!user.name) {
2213
+ return { valid: false, error: 'Name required' }
2214
+ }
2215
+ }
2216
+
2217
+ return { valid: true }
2218
+ }
2219
+ ```
2220
+
2221
+ ### 7.9 Hoist RegExp Creation
2222
+
2223
+ **Impact: LOW-MEDIUM (avoids recreation)**
2224
+
2225
+ Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
2226
+
2227
+ **Incorrect: new RegExp every render**
2228
+
2229
+ ```tsx
2230
+ function Highlighter({ text, query }: Props) {
2231
+ const regex = new RegExp(`(${query})`, 'gi')
2232
+ const parts = text.split(regex)
2233
+ return <>{parts.map((part, i) => ...)}</>
2234
+ }
2235
+ ```
2236
+
2237
+ **Correct: memoize or hoist**
2238
+
2239
+ ```tsx
2240
+ const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
2241
+
2242
+ function Highlighter({ text, query }: Props) {
2243
+ const regex = useMemo(
2244
+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
2245
+ [query]
2246
+ )
2247
+ const parts = text.split(regex)
2248
+ return <>{parts.map((part, i) => ...)}</>
2249
+ }
2250
+ ```
2251
+
2252
+ **Warning: global regex has mutable state**
2253
+
2254
+ ```typescript
2255
+ const regex = /foo/g
2256
+ regex.test('foo') // true, lastIndex = 3
2257
+ regex.test('foo') // false, lastIndex = 0
2258
+ ```
2259
+
2260
+ Global regex (`/g`) has mutable `lastIndex` state:
2261
+
2262
+ ### 7.10 Use Loop for Min/Max Instead of Sort
2263
+
2264
+ **Impact: LOW (O(n) instead of O(n log n))**
2265
+
2266
+ Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
2267
+
2268
+ **Incorrect (O(n log n) - sort to find latest):**
2269
+
2270
+ ```typescript
2271
+ interface Project {
2272
+ id: string
2273
+ name: string
2274
+ updatedAt: number
2275
+ }
2276
+
2277
+ function getLatestProject(projects: Project[]) {
2278
+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
2279
+ return sorted[0]
2280
+ }
2281
+ ```
2282
+
2283
+ Sorts the entire array just to find the maximum value.
2284
+
2285
+ **Incorrect (O(n log n) - sort for oldest and newest):**
2286
+
2287
+ ```typescript
2288
+ function getOldestAndNewest(projects: Project[]) {
2289
+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
2290
+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
2291
+ }
2292
+ ```
2293
+
2294
+ Still sorts unnecessarily when only min/max are needed.
2295
+
2296
+ **Correct (O(n) - single loop):**
2297
+
2298
+ ```typescript
2299
+ function getLatestProject(projects: Project[]) {
2300
+ if (projects.length === 0) return null
2301
+
2302
+ let latest = projects[0]
2303
+
2304
+ for (let i = 1; i < projects.length; i++) {
2305
+ if (projects[i].updatedAt > latest.updatedAt) {
2306
+ latest = projects[i]
2307
+ }
2308
+ }
2309
+
2310
+ return latest
2311
+ }
2312
+
2313
+ function getOldestAndNewest(projects: Project[]) {
2314
+ if (projects.length === 0) return { oldest: null, newest: null }
2315
+
2316
+ let oldest = projects[0]
2317
+ let newest = projects[0]
2318
+
2319
+ for (let i = 1; i < projects.length; i++) {
2320
+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
2321
+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
2322
+ }
2323
+
2324
+ return { oldest, newest }
2325
+ }
2326
+ ```
2327
+
2328
+ Single pass through the array, no copying, no sorting.
2329
+
2330
+ **Alternative: Math.min/Math.max for small arrays**
2331
+
2332
+ ```typescript
2333
+ const numbers = [5, 2, 8, 1, 9]
2334
+ const min = Math.min(...numbers)
2335
+ const max = Math.max(...numbers)
2336
+ ```
2337
+
2338
+ This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
2339
+
2340
+ ### 7.11 Use Set/Map for O(1) Lookups
2341
+
2342
+ **Impact: LOW-MEDIUM (O(n) to O(1))**
2343
+
2344
+ Convert arrays to Set/Map for repeated membership checks.
2345
+
2346
+ **Incorrect (O(n) per check):**
2347
+
2348
+ ```typescript
2349
+ const allowedIds = ['a', 'b', 'c', ...]
2350
+ items.filter(item => allowedIds.includes(item.id))
2351
+ ```
2352
+
2353
+ **Correct (O(1) per check):**
2354
+
2355
+ ```typescript
2356
+ const allowedIds = new Set(['a', 'b', 'c', ...])
2357
+ items.filter(item => allowedIds.has(item.id))
2358
+ ```
2359
+
2360
+ ### 7.12 Use toSorted() Instead of sort() for Immutability
2361
+
2362
+ **Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**
2363
+
2364
+ `.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
2365
+
2366
+ **Incorrect: mutates original array**
2367
+
2368
+ ```typescript
2369
+ function UserList({ users }: { users: User[] }) {
2370
+ // Mutates the users prop array!
2371
+ const sorted = useMemo(
2372
+ () => users.sort((a, b) => a.name.localeCompare(b.name)),
2373
+ [users]
2374
+ )
2375
+ return <div>{sorted.map(renderUser)}</div>
2376
+ }
2377
+ ```
2378
+
2379
+ **Correct: creates new array**
2380
+
2381
+ ```typescript
2382
+ function UserList({ users }: { users: User[] }) {
2383
+ // Creates new sorted array, original unchanged
2384
+ const sorted = useMemo(
2385
+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
2386
+ [users]
2387
+ )
2388
+ return <div>{sorted.map(renderUser)}</div>
2389
+ }
2390
+ ```
2391
+
2392
+ **Why this matters in React:**
2393
+
2394
+ 1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2395
+
2396
+ 2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
2397
+
2398
+ **Browser support: fallback for older browsers**
2399
+
2400
+ ```typescript
2401
+ // Fallback for older browsers
2402
+ const sorted = [...items].sort((a, b) => a.value - b.value)
2403
+ ```
2404
+
2405
+ `.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
2406
+
2407
+ **Other immutable array methods:**
2408
+
2409
+ - `.toSorted()` - immutable sort
2410
+
2411
+ - `.toReversed()` - immutable reverse
2412
+
2413
+ - `.toSpliced()` - immutable splice
2414
+
2415
+ - `.with()` - immutable element replacement
2416
+
2417
+ ---
2418
+
2419
+ ## 8. Advanced Patterns
2420
+
2421
+ **Impact: LOW**
2422
+
2423
+ Advanced patterns for specific cases that require careful implementation.
2424
+
2425
+ ### 8.1 Store Event Handlers in Refs
2426
+
2427
+ **Impact: LOW (stable subscriptions)**
2428
+
2429
+ Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
2430
+
2431
+ **Incorrect: re-subscribes on every render**
2432
+
2433
+ ```tsx
2434
+ function useWindowEvent(event: string, handler: (e) => void) {
2435
+ useEffect(() => {
2436
+ window.addEventListener(event, handler)
2437
+ return () => window.removeEventListener(event, handler)
2438
+ }, [event, handler])
2439
+ }
2440
+ ```
2441
+
2442
+ **Correct: stable subscription**
2443
+
2444
+ ```tsx
2445
+ import { useEffectEvent } from 'react'
2446
+
2447
+ function useWindowEvent(event: string, handler: (e) => void) {
2448
+ const onEvent = useEffectEvent(handler)
2449
+
2450
+ useEffect(() => {
2451
+ window.addEventListener(event, onEvent)
2452
+ return () => window.removeEventListener(event, onEvent)
2453
+ }, [event])
2454
+ }
2455
+ ```
2456
+
2457
+ **Alternative: use `useEffectEvent` if you're on latest React:**
2458
+
2459
+ `useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
2460
+
2461
+ ### 8.2 useLatest for Stable Callback Refs
2462
+
2463
+ **Impact: LOW (prevents effect re-runs)**
2464
+
2465
+ Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
2466
+
2467
+ **Implementation:**
2468
+
2469
+ ```typescript
2470
+ function useLatest<T>(value: T) {
2471
+ const ref = useRef(value)
2472
+ useLayoutEffect(() => {
2473
+ ref.current = value
2474
+ }, [value])
2475
+ return ref
2476
+ }
2477
+ ```
2478
+
2479
+ **Incorrect: effect re-runs on every callback change**
2480
+
2481
+ ```tsx
2482
+ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
2483
+ const [query, setQuery] = useState('')
2484
+
2485
+ useEffect(() => {
2486
+ const timeout = setTimeout(() => onSearch(query), 300)
2487
+ return () => clearTimeout(timeout)
2488
+ }, [query, onSearch])
2489
+ }
2490
+ ```
2491
+
2492
+ **Correct: stable effect, fresh callback**
2493
+
2494
+ ```tsx
2495
+ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
2496
+ const [query, setQuery] = useState('')
2497
+ const onSearchRef = useLatest(onSearch)
2498
+
2499
+ useEffect(() => {
2500
+ const timeout = setTimeout(() => onSearchRef.current(query), 300)
2501
+ return () => clearTimeout(timeout)
2502
+ }, [query])
2503
+ }
2504
+ ```
2505
+
2506
+ ---
2507
+
2508
+ ## References
2509
+
2510
+ 1. [https://react.dev](https://react.dev)
2511
+ 2. [https://nextjs.org](https://nextjs.org)
2512
+ 3. [https://swr.vercel.app](https://swr.vercel.app)
2513
+ 4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
2514
+ 5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
2515
+ 6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
2516
+ 7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)