@sandrinio/vbounce 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 (95) hide show
  1. package/README.md +107 -0
  2. package/bin/vbounce.mjs +165 -0
  3. package/brains/AGENTS.md +129 -0
  4. package/brains/CLAUDE.md +146 -0
  5. package/brains/GEMINI.md +134 -0
  6. package/brains/SETUP.md +180 -0
  7. package/brains/claude-agents/architect.md +140 -0
  8. package/brains/claude-agents/developer.md +69 -0
  9. package/brains/claude-agents/devops.md +219 -0
  10. package/brains/claude-agents/qa.md +112 -0
  11. package/brains/claude-agents/scribe.md +141 -0
  12. package/brains/cursor-rules/vbounce-docs.mdc +41 -0
  13. package/brains/cursor-rules/vbounce-process.mdc +45 -0
  14. package/brains/cursor-rules/vbounce-rules.mdc +26 -0
  15. package/package.json +40 -0
  16. package/skills/agent-team/SKILL.md +425 -0
  17. package/skills/doc-manager/SKILL.md +278 -0
  18. package/skills/lesson/SKILL.md +90 -0
  19. package/skills/react-best-practices/SKILL.md +3014 -0
  20. package/skills/react-best-practices/rules/_sections.md +46 -0
  21. package/skills/react-best-practices/rules/_template.md +28 -0
  22. package/skills/react-best-practices/rules/advanced-event-handler-refs.md +55 -0
  23. package/skills/react-best-practices/rules/advanced-init-once.md +42 -0
  24. package/skills/react-best-practices/rules/advanced-use-latest.md +39 -0
  25. package/skills/react-best-practices/rules/async-api-routes.md +38 -0
  26. package/skills/react-best-practices/rules/async-defer-await.md +80 -0
  27. package/skills/react-best-practices/rules/async-dependencies.md +51 -0
  28. package/skills/react-best-practices/rules/async-parallel.md +28 -0
  29. package/skills/react-best-practices/rules/async-suspense-boundaries.md +99 -0
  30. package/skills/react-best-practices/rules/bundle-barrel-imports.md +59 -0
  31. package/skills/react-best-practices/rules/bundle-conditional.md +31 -0
  32. package/skills/react-best-practices/rules/bundle-defer-third-party.md +49 -0
  33. package/skills/react-best-practices/rules/bundle-dynamic-imports.md +35 -0
  34. package/skills/react-best-practices/rules/bundle-preload.md +50 -0
  35. package/skills/react-best-practices/rules/client-event-listeners.md +74 -0
  36. package/skills/react-best-practices/rules/client-localstorage-schema.md +71 -0
  37. package/skills/react-best-practices/rules/client-passive-event-listeners.md +48 -0
  38. package/skills/react-best-practices/rules/client-swr-dedup.md +56 -0
  39. package/skills/react-best-practices/rules/js-batch-dom-css.md +107 -0
  40. package/skills/react-best-practices/rules/js-cache-function-results.md +80 -0
  41. package/skills/react-best-practices/rules/js-cache-property-access.md +28 -0
  42. package/skills/react-best-practices/rules/js-cache-storage.md +70 -0
  43. package/skills/react-best-practices/rules/js-combine-iterations.md +32 -0
  44. package/skills/react-best-practices/rules/js-early-exit.md +50 -0
  45. package/skills/react-best-practices/rules/js-hoist-regexp.md +45 -0
  46. package/skills/react-best-practices/rules/js-index-maps.md +37 -0
  47. package/skills/react-best-practices/rules/js-length-check-first.md +49 -0
  48. package/skills/react-best-practices/rules/js-min-max-loop.md +82 -0
  49. package/skills/react-best-practices/rules/js-set-map-lookups.md +24 -0
  50. package/skills/react-best-practices/rules/js-tosorted-immutable.md +57 -0
  51. package/skills/react-best-practices/rules/rendering-activity.md +26 -0
  52. package/skills/react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
  53. package/skills/react-best-practices/rules/rendering-conditional-render.md +40 -0
  54. package/skills/react-best-practices/rules/rendering-content-visibility.md +38 -0
  55. package/skills/react-best-practices/rules/rendering-hoist-jsx.md +46 -0
  56. package/skills/react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
  57. package/skills/react-best-practices/rules/rendering-hydration-suppress-warning.md +30 -0
  58. package/skills/react-best-practices/rules/rendering-svg-precision.md +28 -0
  59. package/skills/react-best-practices/rules/rendering-usetransition-loading.md +75 -0
  60. package/skills/react-best-practices/rules/rerender-defer-reads.md +39 -0
  61. package/skills/react-best-practices/rules/rerender-dependencies.md +45 -0
  62. package/skills/react-best-practices/rules/rerender-derived-state-no-effect.md +40 -0
  63. package/skills/react-best-practices/rules/rerender-derived-state.md +29 -0
  64. package/skills/react-best-practices/rules/rerender-functional-setstate.md +74 -0
  65. package/skills/react-best-practices/rules/rerender-lazy-state-init.md +58 -0
  66. package/skills/react-best-practices/rules/rerender-memo-with-default-value.md +38 -0
  67. package/skills/react-best-practices/rules/rerender-memo.md +44 -0
  68. package/skills/react-best-practices/rules/rerender-move-effect-to-event.md +45 -0
  69. package/skills/react-best-practices/rules/rerender-simple-expression-in-memo.md +35 -0
  70. package/skills/react-best-practices/rules/rerender-transitions.md +40 -0
  71. package/skills/react-best-practices/rules/rerender-use-ref-transient-values.md +73 -0
  72. package/skills/react-best-practices/rules/server-after-nonblocking.md +73 -0
  73. package/skills/react-best-practices/rules/server-auth-actions.md +96 -0
  74. package/skills/react-best-practices/rules/server-cache-lru.md +41 -0
  75. package/skills/react-best-practices/rules/server-cache-react.md +76 -0
  76. package/skills/react-best-practices/rules/server-dedup-props.md +65 -0
  77. package/skills/react-best-practices/rules/server-parallel-fetching.md +83 -0
  78. package/skills/react-best-practices/rules/server-serialization.md +38 -0
  79. package/skills/vibe-code-review/SKILL.md +70 -0
  80. package/skills/vibe-code-review/references/deep-audit.md +259 -0
  81. package/skills/vibe-code-review/references/pr-review.md +234 -0
  82. package/skills/vibe-code-review/references/quick-scan.md +178 -0
  83. package/skills/vibe-code-review/references/report-template.md +189 -0
  84. package/skills/vibe-code-review/references/trend-check.md +224 -0
  85. package/skills/vibe-code-review/scripts/generate-snapshot.sh +89 -0
  86. package/skills/vibe-code-review/scripts/pr-analyze.sh +180 -0
  87. package/skills/write-skill/SKILL.md +133 -0
  88. package/templates/charter.md +144 -0
  89. package/templates/delivery_plan.md +188 -0
  90. package/templates/epic.md +200 -0
  91. package/templates/hotfix.md +57 -0
  92. package/templates/risk_registry.md +89 -0
  93. package/templates/roadmap.md +176 -0
  94. package/templates/sprint_report.md +151 -0
  95. package/templates/story.md +150 -0
@@ -0,0 +1,3014 @@
1
+ ---
2
+ title: Cache Storage API Calls
3
+ impact: LOW-MEDIUM
4
+ impactDescription: reduces expensive I/O
5
+ tags: javascript, localStorage, storage, caching, performance
6
+ ---
7
+
8
+ > [!IMPORTANT]
9
+ > **TEMPLATE SKILL**
10
+ > This skill serves as an example of how to drive code writing according to best practices. It MUST be customized or replaced entirely (e.g., `django-best-practices`, `go-best-practices`) according to the specific tech stack the human decides to use.
11
+
12
+ ## Cache Storage API Calls
13
+
14
+ `localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
15
+
16
+ **Incorrect (reads storage on every call):**
17
+
18
+ ```typescript
19
+ function getTheme() {
20
+ return localStorage.getItem('theme') ?? 'light'
21
+ }
22
+ // Called 10 times = 10 storage reads
23
+ ```
24
+
25
+ **Correct (Map cache):**
26
+
27
+ ```typescript
28
+ const storageCache = new Map<string, string | null>()
29
+
30
+ function getLocalStorage(key: string) {
31
+ if (!storageCache.has(key)) {
32
+ storageCache.set(key, localStorage.getItem(key))
33
+ }
34
+ return storageCache.get(key)
35
+ }
36
+
37
+ function setLocalStorage(key: string, value: string) {
38
+ localStorage.setItem(key, value)
39
+ storageCache.set(key, value) // keep cache in sync
40
+ }
41
+ ```
42
+
43
+ Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
44
+
45
+ **Cookie caching:**
46
+
47
+ ```typescript
48
+ let cookieCache: Record<string, string> | null = null
49
+
50
+ function getCookie(name: string) {
51
+ if (!cookieCache) {
52
+ cookieCache = Object.fromEntries(
53
+ document.cookie.split('; ').map(c => c.split('='))
54
+ )
55
+ }
56
+ return cookieCache[name]
57
+ }
58
+ ```
59
+
60
+ **Important (invalidate on external changes):**
61
+
62
+ If storage can change externally (another tab, server-set cookies), invalidate cache:
63
+
64
+ ```typescript
65
+ window.addEventListener('storage', (e) => {
66
+ if (e.key) storageCache.delete(e.key)
67
+ })
68
+
69
+ document.addEventListener('visibilitychange', () => {
70
+ if (document.visibilityState === 'visible') {
71
+ storageCache.clear()
72
+ }
73
+ })
74
+ ```
75
+ ---
76
+ title: Conditional Module Loading
77
+ impact: HIGH
78
+ impactDescription: loads large data only when needed
79
+ tags: bundle, conditional-loading, lazy-loading
80
+ ---
81
+
82
+ ## Conditional Module Loading
83
+
84
+ Load large data or modules only when a feature is activated.
85
+
86
+ **Example (lazy-load animation frames):**
87
+
88
+ ```tsx
89
+ function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
90
+ const [frames, setFrames] = useState<Frame[] | null>(null)
91
+
92
+ useEffect(() => {
93
+ if (enabled && !frames && typeof window !== 'undefined') {
94
+ import('./animation-frames.js')
95
+ .then(mod => setFrames(mod.frames))
96
+ .catch(() => setEnabled(false))
97
+ }
98
+ }, [enabled, frames, setEnabled])
99
+
100
+ if (!frames) return <Skeleton />
101
+ return <Canvas frames={frames} />
102
+ }
103
+ ```
104
+
105
+ The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
106
+ ---
107
+ title: Preload Based on User Intent
108
+ impact: MEDIUM
109
+ impactDescription: reduces perceived latency
110
+ tags: bundle, preload, user-intent, hover
111
+ ---
112
+
113
+ ## Preload Based on User Intent
114
+
115
+ Preload heavy bundles before they're needed to reduce perceived latency.
116
+
117
+ **Example (preload on hover/focus):**
118
+
119
+ ```tsx
120
+ function EditorButton({ onClick }: { onClick: () => void }) {
121
+ const preload = () => {
122
+ if (typeof window !== 'undefined') {
123
+ void import('./monaco-editor')
124
+ }
125
+ }
126
+
127
+ return (
128
+ <button
129
+ onMouseEnter={preload}
130
+ onFocus={preload}
131
+ onClick={onClick}
132
+ >
133
+ Open Editor
134
+ </button>
135
+ )
136
+ }
137
+ ```
138
+
139
+ **Example (preload when feature flag is enabled):**
140
+
141
+ ```tsx
142
+ function FlagsProvider({ children, flags }: Props) {
143
+ useEffect(() => {
144
+ if (flags.editorEnabled && typeof window !== 'undefined') {
145
+ void import('./monaco-editor').then(mod => mod.init())
146
+ }
147
+ }, [flags.editorEnabled])
148
+
149
+ return <FlagsContext.Provider value={flags}>
150
+ {children}
151
+ </FlagsContext.Provider>
152
+ }
153
+ ```
154
+
155
+ The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
156
+ ---
157
+
158
+ title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
159
+ impact: MEDIUM
160
+ impactDescription: restores memoization by using a constant for default value
161
+ tags: rerender, memo, optimization
162
+
163
+ ---
164
+
165
+ ## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
166
+
167
+ When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.
168
+
169
+ To address this issue, extract the default value into a constant.
170
+
171
+ **Incorrect (`onClick` has different values on every rerender):**
172
+
173
+ ```tsx
174
+ const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
175
+ // ...
176
+ })
177
+
178
+ // Used without optional onClick
179
+ <UserAvatar />
180
+ ```
181
+
182
+ **Correct (stable default value):**
183
+
184
+ ```tsx
185
+ const NOOP = () => {};
186
+
187
+ const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
188
+ // ...
189
+ })
190
+
191
+ // Used without optional onClick
192
+ <UserAvatar />
193
+ ```
194
+ ---
195
+ title: Combine Multiple Array Iterations
196
+ impact: LOW-MEDIUM
197
+ impactDescription: reduces iterations
198
+ tags: javascript, arrays, loops, performance
199
+ ---
200
+
201
+ ## Combine Multiple Array Iterations
202
+
203
+ Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
204
+
205
+ **Incorrect (3 iterations):**
206
+
207
+ ```typescript
208
+ const admins = users.filter(u => u.isAdmin)
209
+ const testers = users.filter(u => u.isTester)
210
+ const inactive = users.filter(u => !u.isActive)
211
+ ```
212
+
213
+ **Correct (1 iteration):**
214
+
215
+ ```typescript
216
+ const admins: User[] = []
217
+ const testers: User[] = []
218
+ const inactive: User[] = []
219
+
220
+ for (const user of users) {
221
+ if (user.isAdmin) admins.push(user)
222
+ if (user.isTester) testers.push(user)
223
+ if (!user.isActive) inactive.push(user)
224
+ }
225
+ ```
226
+ ---
227
+ title: useEffectEvent for Stable Callback Refs
228
+ impact: LOW
229
+ impactDescription: prevents effect re-runs
230
+ tags: advanced, hooks, useEffectEvent, refs, optimization
231
+ ---
232
+
233
+ ## useEffectEvent for Stable Callback Refs
234
+
235
+ Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
236
+
237
+ **Incorrect (effect re-runs on every callback change):**
238
+
239
+ ```tsx
240
+ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
241
+ const [query, setQuery] = useState('')
242
+
243
+ useEffect(() => {
244
+ const timeout = setTimeout(() => onSearch(query), 300)
245
+ return () => clearTimeout(timeout)
246
+ }, [query, onSearch])
247
+ }
248
+ ```
249
+
250
+ **Correct (using React's useEffectEvent):**
251
+
252
+ ```tsx
253
+ import { useEffectEvent } from 'react';
254
+
255
+ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
256
+ const [query, setQuery] = useState('')
257
+ const onSearchEvent = useEffectEvent(onSearch)
258
+
259
+ useEffect(() => {
260
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
261
+ return () => clearTimeout(timeout)
262
+ }, [query])
263
+ }
264
+ ```
265
+ ---
266
+ title: Early Length Check for Array Comparisons
267
+ impact: MEDIUM-HIGH
268
+ impactDescription: avoids expensive operations when lengths differ
269
+ tags: javascript, arrays, performance, optimization, comparison
270
+ ---
271
+
272
+ ## Early Length Check for Array Comparisons
273
+
274
+ When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
275
+
276
+ In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
277
+
278
+ **Incorrect (always runs expensive comparison):**
279
+
280
+ ```typescript
281
+ function hasChanges(current: string[], original: string[]) {
282
+ // Always sorts and joins, even when lengths differ
283
+ return current.sort().join() !== original.sort().join()
284
+ }
285
+ ```
286
+
287
+ 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.
288
+
289
+ **Correct (O(1) length check first):**
290
+
291
+ ```typescript
292
+ function hasChanges(current: string[], original: string[]) {
293
+ // Early return if lengths differ
294
+ if (current.length !== original.length) {
295
+ return true
296
+ }
297
+ // Only sort when lengths match
298
+ const currentSorted = current.toSorted()
299
+ const originalSorted = original.toSorted()
300
+ for (let i = 0; i < currentSorted.length; i++) {
301
+ if (currentSorted[i] !== originalSorted[i]) {
302
+ return true
303
+ }
304
+ }
305
+ return false
306
+ }
307
+ ```
308
+
309
+ This new approach is more efficient because:
310
+ - It avoids the overhead of sorting and joining the arrays when lengths differ
311
+ - It avoids consuming memory for the joined strings (especially important for large arrays)
312
+ - It avoids mutating the original arrays
313
+ - It returns early when a difference is found
314
+ ---
315
+ title: Calculate Derived State During Rendering
316
+ impact: MEDIUM
317
+ impactDescription: avoids redundant renders and state drift
318
+ tags: rerender, derived-state, useEffect, state
319
+ ---
320
+
321
+ ## Calculate Derived State During Rendering
322
+
323
+ If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
324
+
325
+ **Incorrect (redundant state and effect):**
326
+
327
+ ```tsx
328
+ function Form() {
329
+ const [firstName, setFirstName] = useState('First')
330
+ const [lastName, setLastName] = useState('Last')
331
+ const [fullName, setFullName] = useState('')
332
+
333
+ useEffect(() => {
334
+ setFullName(firstName + ' ' + lastName)
335
+ }, [firstName, lastName])
336
+
337
+ return <p>{fullName}</p>
338
+ }
339
+ ```
340
+
341
+ **Correct (derive during render):**
342
+
343
+ ```tsx
344
+ function Form() {
345
+ const [firstName, setFirstName] = useState('First')
346
+ const [lastName, setLastName] = useState('Last')
347
+ const fullName = firstName + ' ' + lastName
348
+
349
+ return <p>{fullName}</p>
350
+ }
351
+ ```
352
+
353
+ References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
354
+ ---
355
+ title: Subscribe to Derived State
356
+ impact: MEDIUM
357
+ impactDescription: reduces re-render frequency
358
+ tags: rerender, derived-state, media-query, optimization
359
+ ---
360
+
361
+ ## Subscribe to Derived State
362
+
363
+ Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
364
+
365
+ **Incorrect (re-renders on every pixel change):**
366
+
367
+ ```tsx
368
+ function Sidebar() {
369
+ const width = useWindowWidth() // updates continuously
370
+ const isMobile = width < 768
371
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
372
+ }
373
+ ```
374
+
375
+ **Correct (re-renders only when boolean changes):**
376
+
377
+ ```tsx
378
+ function Sidebar() {
379
+ const isMobile = useMediaQuery('(max-width: 767px)')
380
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
381
+ }
382
+ ```
383
+ ---
384
+ title: Defer Await Until Needed
385
+ impact: HIGH
386
+ impactDescription: avoids blocking unused code paths
387
+ tags: async, await, conditional, optimization
388
+ ---
389
+
390
+ ## Defer Await Until Needed
391
+
392
+ Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
393
+
394
+ **Incorrect (blocks both branches):**
395
+
396
+ ```typescript
397
+ async function handleRequest(userId: string, skipProcessing: boolean) {
398
+ const userData = await fetchUserData(userId)
399
+
400
+ if (skipProcessing) {
401
+ // Returns immediately but still waited for userData
402
+ return { skipped: true }
403
+ }
404
+
405
+ // Only this branch uses userData
406
+ return processUserData(userData)
407
+ }
408
+ ```
409
+
410
+ **Correct (only blocks when needed):**
411
+
412
+ ```typescript
413
+ async function handleRequest(userId: string, skipProcessing: boolean) {
414
+ if (skipProcessing) {
415
+ // Returns immediately without waiting
416
+ return { skipped: true }
417
+ }
418
+
419
+ // Fetch only when needed
420
+ const userData = await fetchUserData(userId)
421
+ return processUserData(userData)
422
+ }
423
+ ```
424
+
425
+ **Another example (early return optimization):**
426
+
427
+ ```typescript
428
+ // Incorrect: always fetches permissions
429
+ async function updateResource(resourceId: string, userId: string) {
430
+ const permissions = await fetchPermissions(userId)
431
+ const resource = await getResource(resourceId)
432
+
433
+ if (!resource) {
434
+ return { error: 'Not found' }
435
+ }
436
+
437
+ if (!permissions.canEdit) {
438
+ return { error: 'Forbidden' }
439
+ }
440
+
441
+ return await updateResourceData(resource, permissions)
442
+ }
443
+
444
+ // Correct: fetches only when needed
445
+ async function updateResource(resourceId: string, userId: string) {
446
+ const resource = await getResource(resourceId)
447
+
448
+ if (!resource) {
449
+ return { error: 'Not found' }
450
+ }
451
+
452
+ const permissions = await fetchPermissions(userId)
453
+
454
+ if (!permissions.canEdit) {
455
+ return { error: 'Forbidden' }
456
+ }
457
+
458
+ return await updateResourceData(resource, permissions)
459
+ }
460
+ ```
461
+
462
+ This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
463
+ ---
464
+ title: Strategic Suspense Boundaries
465
+ impact: HIGH
466
+ impactDescription: faster initial paint
467
+ tags: async, suspense, streaming, layout-shift
468
+ ---
469
+
470
+ ## Strategic Suspense Boundaries
471
+
472
+ Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
473
+
474
+ **Incorrect (wrapper blocked by data fetching):**
475
+
476
+ ```tsx
477
+ async function Page() {
478
+ const data = await fetchData() // Blocks entire page
479
+
480
+ return (
481
+ <div>
482
+ <div>Sidebar</div>
483
+ <div>Header</div>
484
+ <div>
485
+ <DataDisplay data={data} />
486
+ </div>
487
+ <div>Footer</div>
488
+ </div>
489
+ )
490
+ }
491
+ ```
492
+
493
+ The entire layout waits for data even though only the middle section needs it.
494
+
495
+ **Correct (wrapper shows immediately, data streams in):**
496
+
497
+ ```tsx
498
+ function Page() {
499
+ return (
500
+ <div>
501
+ <div>Sidebar</div>
502
+ <div>Header</div>
503
+ <div>
504
+ <Suspense fallback={<Skeleton />}>
505
+ <DataDisplay />
506
+ </Suspense>
507
+ </div>
508
+ <div>Footer</div>
509
+ </div>
510
+ )
511
+ }
512
+
513
+ async function DataDisplay() {
514
+ const data = await fetchData() // Only blocks this component
515
+ return <div>{data.content}</div>
516
+ }
517
+ ```
518
+
519
+ Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
520
+
521
+ **Alternative (share promise across components):**
522
+
523
+ ```tsx
524
+ function Page() {
525
+ // Start fetch immediately, but don't await
526
+ const dataPromise = fetchData()
527
+
528
+ return (
529
+ <div>
530
+ <div>Sidebar</div>
531
+ <div>Header</div>
532
+ <Suspense fallback={<Skeleton />}>
533
+ <DataDisplay dataPromise={dataPromise} />
534
+ <DataSummary dataPromise={dataPromise} />
535
+ </Suspense>
536
+ <div>Footer</div>
537
+ </div>
538
+ )
539
+ }
540
+
541
+ function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
542
+ const data = use(dataPromise) // Unwraps the promise
543
+ return <div>{data.content}</div>
544
+ }
545
+
546
+ function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
547
+ const data = use(dataPromise) // Reuses the same promise
548
+ return <div>{data.summary}</div>
549
+ }
550
+ ```
551
+
552
+ Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
553
+
554
+ **When NOT to use this pattern:**
555
+
556
+ - Critical data needed for layout decisions (affects positioning)
557
+ - SEO-critical content above the fold
558
+ - Small, fast queries where suspense overhead isn't worth it
559
+ - When you want to avoid layout shift (loading → content jump)
560
+
561
+ **Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
562
+ ---
563
+ title: Use Activity Component for Show/Hide
564
+ impact: MEDIUM
565
+ impactDescription: preserves state/DOM
566
+ tags: rendering, activity, visibility, state-preservation
567
+ ---
568
+
569
+ ## Use Activity Component for Show/Hide
570
+
571
+ Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
572
+
573
+ **Usage:**
574
+
575
+ ```tsx
576
+ import { Activity } from 'react'
577
+
578
+ function Dropdown({ isOpen }: Props) {
579
+ return (
580
+ <Activity mode={isOpen ? 'visible' : 'hidden'}>
581
+ <ExpensiveMenu />
582
+ </Activity>
583
+ )
584
+ }
585
+ ```
586
+
587
+ Avoids expensive re-renders and state loss.
588
+ ---
589
+ title: Avoid Duplicate Serialization in RSC Props
590
+ impact: LOW
591
+ impactDescription: reduces network payload by avoiding duplicate serialization
592
+ tags: server, rsc, serialization, props, client-components
593
+ ---
594
+
595
+ ## Avoid Duplicate Serialization in RSC Props
596
+
597
+ **Impact: LOW (reduces network payload by avoiding duplicate serialization)**
598
+
599
+ 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.
600
+
601
+ **Incorrect (duplicates array):**
602
+
603
+ ```tsx
604
+ // RSC: sends 6 strings (2 arrays × 3 items)
605
+ <ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
606
+ ```
607
+
608
+ **Correct (sends 3 strings):**
609
+
610
+ ```tsx
611
+ // RSC: send once
612
+ <ClientList usernames={usernames} />
613
+
614
+ // Client: transform there
615
+ 'use client'
616
+ const sorted = useMemo(() => [...usernames].sort(), [usernames])
617
+ ```
618
+
619
+ **Nested deduplication behavior:**
620
+
621
+ Deduplication works recursively. Impact varies by data type:
622
+
623
+ - `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
624
+ - `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
625
+
626
+ ```tsx
627
+ // string[] - duplicates everything
628
+ usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
629
+
630
+ // object[] - duplicates array structure only
631
+ users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
632
+ ```
633
+
634
+ **Operations breaking deduplication (create new references):**
635
+
636
+ - Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
637
+ - Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
638
+
639
+ **More examples:**
640
+
641
+ ```tsx
642
+ // ❌ Bad
643
+ <C users={users} active={users.filter(u => u.active)} />
644
+ <C product={product} productName={product.name} />
645
+
646
+ // ✅ Good
647
+ <C users={users} />
648
+ <C product={product} />
649
+ // Do filtering/destructuring in client
650
+ ```
651
+
652
+ **Exception:** Pass derived data when transformation is expensive or client doesn't need original.
653
+ ---
654
+ title: Put Interaction Logic in Event Handlers
655
+ impact: MEDIUM
656
+ impactDescription: avoids effect re-runs and duplicate side effects
657
+ tags: rerender, useEffect, events, side-effects, dependencies
658
+ ---
659
+
660
+ ## Put Interaction Logic in Event Handlers
661
+
662
+ If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
663
+
664
+ **Incorrect (event modeled as state + effect):**
665
+
666
+ ```tsx
667
+ function Form() {
668
+ const [submitted, setSubmitted] = useState(false)
669
+ const theme = useContext(ThemeContext)
670
+
671
+ useEffect(() => {
672
+ if (submitted) {
673
+ post('/api/register')
674
+ showToast('Registered', theme)
675
+ }
676
+ }, [submitted, theme])
677
+
678
+ return <button onClick={() => setSubmitted(true)}>Submit</button>
679
+ }
680
+ ```
681
+
682
+ **Correct (do it in the handler):**
683
+
684
+ ```tsx
685
+ function Form() {
686
+ const theme = useContext(ThemeContext)
687
+
688
+ function handleSubmit() {
689
+ post('/api/register')
690
+ showToast('Registered', theme)
691
+ }
692
+
693
+ return <button onClick={handleSubmit}>Submit</button>
694
+ }
695
+ ```
696
+
697
+ Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
698
+ ---
699
+ title: Defer State Reads to Usage Point
700
+ impact: MEDIUM
701
+ impactDescription: avoids unnecessary subscriptions
702
+ tags: rerender, searchParams, localStorage, optimization
703
+ ---
704
+
705
+ ## Defer State Reads to Usage Point
706
+
707
+ Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
708
+
709
+ **Incorrect (subscribes to all searchParams changes):**
710
+
711
+ ```tsx
712
+ function ShareButton({ chatId }: { chatId: string }) {
713
+ const searchParams = useSearchParams()
714
+
715
+ const handleShare = () => {
716
+ const ref = searchParams.get('ref')
717
+ shareChat(chatId, { ref })
718
+ }
719
+
720
+ return <button onClick={handleShare}>Share</button>
721
+ }
722
+ ```
723
+
724
+ **Correct (reads on demand, no subscription):**
725
+
726
+ ```tsx
727
+ function ShareButton({ chatId }: { chatId: string }) {
728
+ const handleShare = () => {
729
+ const params = new URLSearchParams(window.location.search)
730
+ const ref = params.get('ref')
731
+ shareChat(chatId, { ref })
732
+ }
733
+
734
+ return <button onClick={handleShare}>Share</button>
735
+ }
736
+ ```
737
+ ---
738
+ title: Prevent Waterfall Chains in API Routes
739
+ impact: CRITICAL
740
+ impactDescription: 2-10× improvement
741
+ tags: api-routes, server-actions, waterfalls, parallelization
742
+ ---
743
+
744
+ ## Prevent Waterfall Chains in API Routes
745
+
746
+ In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
747
+
748
+ **Incorrect (config waits for auth, data waits for both):**
749
+
750
+ ```typescript
751
+ export async function GET(request: Request) {
752
+ const session = await auth()
753
+ const config = await fetchConfig()
754
+ const data = await fetchData(session.user.id)
755
+ return Response.json({ data, config })
756
+ }
757
+ ```
758
+
759
+ **Correct (auth and config start immediately):**
760
+
761
+ ```typescript
762
+ export async function GET(request: Request) {
763
+ const sessionPromise = auth()
764
+ const configPromise = fetchConfig()
765
+ const session = await sessionPromise
766
+ const [config, data] = await Promise.all([
767
+ configPromise,
768
+ fetchData(session.user.id)
769
+ ])
770
+ return Response.json({ data, config })
771
+ }
772
+ ```
773
+
774
+ For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
775
+ ---
776
+ title: Suppress Expected Hydration Mismatches
777
+ impact: LOW-MEDIUM
778
+ impactDescription: avoids noisy hydration warnings for known differences
779
+ tags: rendering, hydration, ssr, nextjs
780
+ ---
781
+
782
+ ## Suppress Expected Hydration Mismatches
783
+
784
+ In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
785
+
786
+ **Incorrect (known mismatch warnings):**
787
+
788
+ ```tsx
789
+ function Timestamp() {
790
+ return <span>{new Date().toLocaleString()}</span>
791
+ }
792
+ ```
793
+
794
+ **Correct (suppress expected mismatch only):**
795
+
796
+ ```tsx
797
+ function Timestamp() {
798
+ return (
799
+ <span suppressHydrationWarning>
800
+ {new Date().toLocaleString()}
801
+ </span>
802
+ )
803
+ }
804
+ ```
805
+ ---
806
+ title: Narrow Effect Dependencies
807
+ impact: LOW
808
+ impactDescription: minimizes effect re-runs
809
+ tags: rerender, useEffect, dependencies, optimization
810
+ ---
811
+
812
+ ## Narrow Effect Dependencies
813
+
814
+ Specify primitive dependencies instead of objects to minimize effect re-runs.
815
+
816
+ **Incorrect (re-runs on any user field change):**
817
+
818
+ ```tsx
819
+ useEffect(() => {
820
+ console.log(user.id)
821
+ }, [user])
822
+ ```
823
+
824
+ **Correct (re-runs only when id changes):**
825
+
826
+ ```tsx
827
+ useEffect(() => {
828
+ console.log(user.id)
829
+ }, [user.id])
830
+ ```
831
+
832
+ **For derived state, compute outside effect:**
833
+
834
+ ```tsx
835
+ // Incorrect: runs on width=767, 766, 765...
836
+ useEffect(() => {
837
+ if (width < 768) {
838
+ enableMobileMode()
839
+ }
840
+ }, [width])
841
+
842
+ // Correct: runs only on boolean transition
843
+ const isMobile = width < 768
844
+ useEffect(() => {
845
+ if (isMobile) {
846
+ enableMobileMode()
847
+ }
848
+ }, [isMobile])
849
+ ```
850
+ ---
851
+ title: Use Set/Map for O(1) Lookups
852
+ impact: LOW-MEDIUM
853
+ impactDescription: O(n) to O(1)
854
+ tags: javascript, set, map, data-structures, performance
855
+ ---
856
+
857
+ ## Use Set/Map for O(1) Lookups
858
+
859
+ Convert arrays to Set/Map for repeated membership checks.
860
+
861
+ **Incorrect (O(n) per check):**
862
+
863
+ ```typescript
864
+ const allowedIds = ['a', 'b', 'c', ...]
865
+ items.filter(item => allowedIds.includes(item.id))
866
+ ```
867
+
868
+ **Correct (O(1) per check):**
869
+
870
+ ```typescript
871
+ const allowedIds = new Set(['a', 'b', 'c', ...])
872
+ items.filter(item => allowedIds.has(item.id))
873
+ ```
874
+ ---
875
+ title: Defer Non-Critical Third-Party Libraries
876
+ impact: MEDIUM
877
+ impactDescription: loads after hydration
878
+ tags: bundle, third-party, analytics, defer
879
+ ---
880
+
881
+ ## Defer Non-Critical Third-Party Libraries
882
+
883
+ Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
884
+
885
+ **Incorrect (blocks initial bundle):**
886
+
887
+ ```tsx
888
+ import { Analytics } from '@vercel/analytics/react'
889
+
890
+ export default function RootLayout({ children }) {
891
+ return (
892
+ <html>
893
+ <body>
894
+ {children}
895
+ <Analytics />
896
+ </body>
897
+ </html>
898
+ )
899
+ }
900
+ ```
901
+
902
+ **Correct (loads after hydration):**
903
+
904
+ ```tsx
905
+ import dynamic from 'next/dynamic'
906
+
907
+ const Analytics = dynamic(
908
+ () => import('@vercel/analytics/react').then(m => m.Analytics),
909
+ { ssr: false }
910
+ )
911
+
912
+ export default function RootLayout({ children }) {
913
+ return (
914
+ <html>
915
+ <body>
916
+ {children}
917
+ <Analytics />
918
+ </body>
919
+ </html>
920
+ )
921
+ }
922
+ ```
923
+ ---
924
+ title: Hoist Static JSX Elements
925
+ impact: LOW
926
+ impactDescription: avoids re-creation
927
+ tags: rendering, jsx, static, optimization
928
+ ---
929
+
930
+ ## Hoist Static JSX Elements
931
+
932
+ Extract static JSX outside components to avoid re-creation.
933
+
934
+ **Incorrect (recreates element every render):**
935
+
936
+ ```tsx
937
+ function LoadingSkeleton() {
938
+ return <div className="animate-pulse h-20 bg-gray-200" />
939
+ }
940
+
941
+ function Container() {
942
+ return (
943
+ <div>
944
+ {loading && <LoadingSkeleton />}
945
+ </div>
946
+ )
947
+ }
948
+ ```
949
+
950
+ **Correct (reuses same element):**
951
+
952
+ ```tsx
953
+ const loadingSkeleton = (
954
+ <div className="animate-pulse h-20 bg-gray-200" />
955
+ )
956
+
957
+ function Container() {
958
+ return (
959
+ <div>
960
+ {loading && loadingSkeleton}
961
+ </div>
962
+ )
963
+ }
964
+ ```
965
+
966
+ This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
967
+
968
+ **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.
969
+ ---
970
+ title: Dependency-Based Parallelization
971
+ impact: CRITICAL
972
+ impactDescription: 2-10× improvement
973
+ tags: async, parallelization, dependencies, better-all
974
+ ---
975
+
976
+ ## Dependency-Based Parallelization
977
+
978
+ For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
979
+
980
+ **Incorrect (profile waits for config unnecessarily):**
981
+
982
+ ```typescript
983
+ const [user, config] = await Promise.all([
984
+ fetchUser(),
985
+ fetchConfig()
986
+ ])
987
+ const profile = await fetchProfile(user.id)
988
+ ```
989
+
990
+ **Correct (config and profile run in parallel):**
991
+
992
+ ```typescript
993
+ import { all } from 'better-all'
994
+
995
+ const { user, config, profile } = await all({
996
+ async user() { return fetchUser() },
997
+ async config() { return fetchConfig() },
998
+ async profile() {
999
+ return fetchProfile((await this.$.user).id)
1000
+ }
1001
+ })
1002
+ ```
1003
+
1004
+ **Alternative without extra dependencies:**
1005
+
1006
+ We can also create all the promises first, and do `Promise.all()` at the end.
1007
+
1008
+ ```typescript
1009
+ const userPromise = fetchUser()
1010
+ const profilePromise = userPromise.then(user => fetchProfile(user.id))
1011
+
1012
+ const [user, config, profile] = await Promise.all([
1013
+ userPromise,
1014
+ fetchConfig(),
1015
+ profilePromise
1016
+ ])
1017
+ ```
1018
+
1019
+ Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
1020
+ ---
1021
+ title: Use useRef for Transient Values
1022
+ impact: MEDIUM
1023
+ impactDescription: avoids unnecessary re-renders on frequent updates
1024
+ tags: rerender, useref, state, performance
1025
+ ---
1026
+
1027
+ ## Use useRef for Transient Values
1028
+
1029
+ When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
1030
+
1031
+ **Incorrect (renders every update):**
1032
+
1033
+ ```tsx
1034
+ function Tracker() {
1035
+ const [lastX, setLastX] = useState(0)
1036
+
1037
+ useEffect(() => {
1038
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
1039
+ window.addEventListener('mousemove', onMove)
1040
+ return () => window.removeEventListener('mousemove', onMove)
1041
+ }, [])
1042
+
1043
+ return (
1044
+ <div
1045
+ style={{
1046
+ position: 'fixed',
1047
+ top: 0,
1048
+ left: lastX,
1049
+ width: 8,
1050
+ height: 8,
1051
+ background: 'black',
1052
+ }}
1053
+ />
1054
+ )
1055
+ }
1056
+ ```
1057
+
1058
+ **Correct (no re-render for tracking):**
1059
+
1060
+ ```tsx
1061
+ function Tracker() {
1062
+ const lastXRef = useRef(0)
1063
+ const dotRef = useRef<HTMLDivElement>(null)
1064
+
1065
+ useEffect(() => {
1066
+ const onMove = (e: MouseEvent) => {
1067
+ lastXRef.current = e.clientX
1068
+ const node = dotRef.current
1069
+ if (node) {
1070
+ node.style.transform = `translateX(${e.clientX}px)`
1071
+ }
1072
+ }
1073
+ window.addEventListener('mousemove', onMove)
1074
+ return () => window.removeEventListener('mousemove', onMove)
1075
+ }, [])
1076
+
1077
+ return (
1078
+ <div
1079
+ ref={dotRef}
1080
+ style={{
1081
+ position: 'fixed',
1082
+ top: 0,
1083
+ left: 0,
1084
+ width: 8,
1085
+ height: 8,
1086
+ background: 'black',
1087
+ transform: 'translateX(0px)',
1088
+ }}
1089
+ />
1090
+ )
1091
+ }
1092
+ ```
1093
+ ---
1094
+ title: Use Loop for Min/Max Instead of Sort
1095
+ impact: LOW
1096
+ impactDescription: O(n) instead of O(n log n)
1097
+ tags: javascript, arrays, performance, sorting, algorithms
1098
+ ---
1099
+
1100
+ ## Use Loop for Min/Max Instead of Sort
1101
+
1102
+ Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
1103
+
1104
+ **Incorrect (O(n log n) - sort to find latest):**
1105
+
1106
+ ```typescript
1107
+ interface Project {
1108
+ id: string
1109
+ name: string
1110
+ updatedAt: number
1111
+ }
1112
+
1113
+ function getLatestProject(projects: Project[]) {
1114
+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
1115
+ return sorted[0]
1116
+ }
1117
+ ```
1118
+
1119
+ Sorts the entire array just to find the maximum value.
1120
+
1121
+ **Incorrect (O(n log n) - sort for oldest and newest):**
1122
+
1123
+ ```typescript
1124
+ function getOldestAndNewest(projects: Project[]) {
1125
+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
1126
+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
1127
+ }
1128
+ ```
1129
+
1130
+ Still sorts unnecessarily when only min/max are needed.
1131
+
1132
+ **Correct (O(n) - single loop):**
1133
+
1134
+ ```typescript
1135
+ function getLatestProject(projects: Project[]) {
1136
+ if (projects.length === 0) return null
1137
+
1138
+ let latest = projects[0]
1139
+
1140
+ for (let i = 1; i < projects.length; i++) {
1141
+ if (projects[i].updatedAt > latest.updatedAt) {
1142
+ latest = projects[i]
1143
+ }
1144
+ }
1145
+
1146
+ return latest
1147
+ }
1148
+
1149
+ function getOldestAndNewest(projects: Project[]) {
1150
+ if (projects.length === 0) return { oldest: null, newest: null }
1151
+
1152
+ let oldest = projects[0]
1153
+ let newest = projects[0]
1154
+
1155
+ for (let i = 1; i < projects.length; i++) {
1156
+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
1157
+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
1158
+ }
1159
+
1160
+ return { oldest, newest }
1161
+ }
1162
+ ```
1163
+
1164
+ Single pass through the array, no copying, no sorting.
1165
+
1166
+ **Alternative (Math.min/Math.max for small arrays):**
1167
+
1168
+ ```typescript
1169
+ const numbers = [5, 2, 8, 1, 9]
1170
+ const min = Math.min(...numbers)
1171
+ const max = Math.max(...numbers)
1172
+ ```
1173
+
1174
+ 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.
1175
+ ---
1176
+ title: Cache Property Access in Loops
1177
+ impact: LOW-MEDIUM
1178
+ impactDescription: reduces lookups
1179
+ tags: javascript, loops, optimization, caching
1180
+ ---
1181
+
1182
+ ## Cache Property Access in Loops
1183
+
1184
+ Cache object property lookups in hot paths.
1185
+
1186
+ **Incorrect (3 lookups × N iterations):**
1187
+
1188
+ ```typescript
1189
+ for (let i = 0; i < arr.length; i++) {
1190
+ process(obj.config.settings.value)
1191
+ }
1192
+ ```
1193
+
1194
+ **Correct (1 lookup total):**
1195
+
1196
+ ```typescript
1197
+ const value = obj.config.settings.value
1198
+ const len = arr.length
1199
+ for (let i = 0; i < len; i++) {
1200
+ process(value)
1201
+ }
1202
+ ```
1203
+ ---
1204
+ title: Animate SVG Wrapper Instead of SVG Element
1205
+ impact: LOW
1206
+ impactDescription: enables hardware acceleration
1207
+ tags: rendering, svg, css, animation, performance
1208
+ ---
1209
+
1210
+ ## Animate SVG Wrapper Instead of SVG Element
1211
+
1212
+ Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
1213
+
1214
+ **Incorrect (animating SVG directly - no hardware acceleration):**
1215
+
1216
+ ```tsx
1217
+ function LoadingSpinner() {
1218
+ return (
1219
+ <svg
1220
+ className="animate-spin"
1221
+ width="24"
1222
+ height="24"
1223
+ viewBox="0 0 24 24"
1224
+ >
1225
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
1226
+ </svg>
1227
+ )
1228
+ }
1229
+ ```
1230
+
1231
+ **Correct (animating wrapper div - hardware accelerated):**
1232
+
1233
+ ```tsx
1234
+ function LoadingSpinner() {
1235
+ return (
1236
+ <div className="animate-spin">
1237
+ <svg
1238
+ width="24"
1239
+ height="24"
1240
+ viewBox="0 0 24 24"
1241
+ >
1242
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
1243
+ </svg>
1244
+ </div>
1245
+ )
1246
+ }
1247
+ ```
1248
+
1249
+ 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.
1250
+ ---
1251
+ title: Early Return from Functions
1252
+ impact: LOW-MEDIUM
1253
+ impactDescription: avoids unnecessary computation
1254
+ tags: javascript, functions, optimization, early-return
1255
+ ---
1256
+
1257
+ ## Early Return from Functions
1258
+
1259
+ Return early when result is determined to skip unnecessary processing.
1260
+
1261
+ **Incorrect (processes all items even after finding answer):**
1262
+
1263
+ ```typescript
1264
+ function validateUsers(users: User[]) {
1265
+ let hasError = false
1266
+ let errorMessage = ''
1267
+
1268
+ for (const user of users) {
1269
+ if (!user.email) {
1270
+ hasError = true
1271
+ errorMessage = 'Email required'
1272
+ }
1273
+ if (!user.name) {
1274
+ hasError = true
1275
+ errorMessage = 'Name required'
1276
+ }
1277
+ // Continues checking all users even after error found
1278
+ }
1279
+
1280
+ return hasError ? { valid: false, error: errorMessage } : { valid: true }
1281
+ }
1282
+ ```
1283
+
1284
+ **Correct (returns immediately on first error):**
1285
+
1286
+ ```typescript
1287
+ function validateUsers(users: User[]) {
1288
+ for (const user of users) {
1289
+ if (!user.email) {
1290
+ return { valid: false, error: 'Email required' }
1291
+ }
1292
+ if (!user.name) {
1293
+ return { valid: false, error: 'Name required' }
1294
+ }
1295
+ }
1296
+
1297
+ return { valid: true }
1298
+ }
1299
+ ```
1300
+ ---
1301
+ title: Build Index Maps for Repeated Lookups
1302
+ impact: LOW-MEDIUM
1303
+ impactDescription: 1M ops to 2K ops
1304
+ tags: javascript, map, indexing, optimization, performance
1305
+ ---
1306
+
1307
+ ## Build Index Maps for Repeated Lookups
1308
+
1309
+ Multiple `.find()` calls by the same key should use a Map.
1310
+
1311
+ **Incorrect (O(n) per lookup):**
1312
+
1313
+ ```typescript
1314
+ function processOrders(orders: Order[], users: User[]) {
1315
+ return orders.map(order => ({
1316
+ ...order,
1317
+ user: users.find(u => u.id === order.userId)
1318
+ }))
1319
+ }
1320
+ ```
1321
+
1322
+ **Correct (O(1) per lookup):**
1323
+
1324
+ ```typescript
1325
+ function processOrders(orders: Order[], users: User[]) {
1326
+ const userById = new Map(users.map(u => [u.id, u]))
1327
+
1328
+ return orders.map(order => ({
1329
+ ...order,
1330
+ user: userById.get(order.userId)
1331
+ }))
1332
+ }
1333
+ ```
1334
+
1335
+ Build map once (O(n)), then all lookups are O(1).
1336
+ For 1000 orders × 1000 users: 1M ops → 2K ops.
1337
+ ---
1338
+ title: Parallel Data Fetching with Component Composition
1339
+ impact: CRITICAL
1340
+ impactDescription: eliminates server-side waterfalls
1341
+ tags: server, rsc, parallel-fetching, composition
1342
+ ---
1343
+
1344
+ ## Parallel Data Fetching with Component Composition
1345
+
1346
+ React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
1347
+
1348
+ **Incorrect (Sidebar waits for Page's fetch to complete):**
1349
+
1350
+ ```tsx
1351
+ export default async function Page() {
1352
+ const header = await fetchHeader()
1353
+ return (
1354
+ <div>
1355
+ <div>{header}</div>
1356
+ <Sidebar />
1357
+ </div>
1358
+ )
1359
+ }
1360
+
1361
+ async function Sidebar() {
1362
+ const items = await fetchSidebarItems()
1363
+ return <nav>{items.map(renderItem)}</nav>
1364
+ }
1365
+ ```
1366
+
1367
+ **Correct (both fetch simultaneously):**
1368
+
1369
+ ```tsx
1370
+ async function Header() {
1371
+ const data = await fetchHeader()
1372
+ return <div>{data}</div>
1373
+ }
1374
+
1375
+ async function Sidebar() {
1376
+ const items = await fetchSidebarItems()
1377
+ return <nav>{items.map(renderItem)}</nav>
1378
+ }
1379
+
1380
+ export default function Page() {
1381
+ return (
1382
+ <div>
1383
+ <Header />
1384
+ <Sidebar />
1385
+ </div>
1386
+ )
1387
+ }
1388
+ ```
1389
+
1390
+ **Alternative with children prop:**
1391
+
1392
+ ```tsx
1393
+ async function Header() {
1394
+ const data = await fetchHeader()
1395
+ return <div>{data}</div>
1396
+ }
1397
+
1398
+ async function Sidebar() {
1399
+ const items = await fetchSidebarItems()
1400
+ return <nav>{items.map(renderItem)}</nav>
1401
+ }
1402
+
1403
+ function Layout({ children }: { children: ReactNode }) {
1404
+ return (
1405
+ <div>
1406
+ <Header />
1407
+ {children}
1408
+ </div>
1409
+ )
1410
+ }
1411
+
1412
+ export default function Page() {
1413
+ return (
1414
+ <Layout>
1415
+ <Sidebar />
1416
+ </Layout>
1417
+ )
1418
+ }
1419
+ ```
1420
+ ---
1421
+ title: Cross-Request LRU Caching
1422
+ impact: HIGH
1423
+ impactDescription: caches across requests
1424
+ tags: server, cache, lru, cross-request
1425
+ ---
1426
+
1427
+ ## Cross-Request LRU Caching
1428
+
1429
+ `React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
1430
+
1431
+ **Implementation:**
1432
+
1433
+ ```typescript
1434
+ import { LRUCache } from 'lru-cache'
1435
+
1436
+ const cache = new LRUCache<string, any>({
1437
+ max: 1000,
1438
+ ttl: 5 * 60 * 1000 // 5 minutes
1439
+ })
1440
+
1441
+ export async function getUser(id: string) {
1442
+ const cached = cache.get(id)
1443
+ if (cached) return cached
1444
+
1445
+ const user = await db.user.findUnique({ where: { id } })
1446
+ cache.set(id, user)
1447
+ return user
1448
+ }
1449
+
1450
+ // Request 1: DB query, result cached
1451
+ // Request 2: cache hit, no DB query
1452
+ ```
1453
+
1454
+ Use when sequential user actions hit multiple endpoints needing the same data within seconds.
1455
+
1456
+ **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.
1457
+
1458
+ **In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
1459
+
1460
+ Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
1461
+ ---
1462
+ title: Use Passive Event Listeners for Scrolling Performance
1463
+ impact: MEDIUM
1464
+ impactDescription: eliminates scroll delay caused by event listeners
1465
+ tags: client, event-listeners, scrolling, performance, touch, wheel
1466
+ ---
1467
+
1468
+ ## Use Passive Event Listeners for Scrolling Performance
1469
+
1470
+ 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.
1471
+
1472
+ **Incorrect:**
1473
+
1474
+ ```typescript
1475
+ useEffect(() => {
1476
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
1477
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
1478
+
1479
+ document.addEventListener('touchstart', handleTouch)
1480
+ document.addEventListener('wheel', handleWheel)
1481
+
1482
+ return () => {
1483
+ document.removeEventListener('touchstart', handleTouch)
1484
+ document.removeEventListener('wheel', handleWheel)
1485
+ }
1486
+ }, [])
1487
+ ```
1488
+
1489
+ **Correct:**
1490
+
1491
+ ```typescript
1492
+ useEffect(() => {
1493
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
1494
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
1495
+
1496
+ document.addEventListener('touchstart', handleTouch, { passive: true })
1497
+ document.addEventListener('wheel', handleWheel, { passive: true })
1498
+
1499
+ return () => {
1500
+ document.removeEventListener('touchstart', handleTouch)
1501
+ document.removeEventListener('wheel', handleWheel)
1502
+ }
1503
+ }, [])
1504
+ ```
1505
+
1506
+ **Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
1507
+
1508
+ **Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
1509
+ ---
1510
+ title: Use useTransition Over Manual Loading States
1511
+ impact: LOW
1512
+ impactDescription: reduces re-renders and improves code clarity
1513
+ tags: rendering, transitions, useTransition, loading, state
1514
+ ---
1515
+
1516
+ ## Use useTransition Over Manual Loading States
1517
+
1518
+ Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
1519
+
1520
+ **Incorrect (manual loading state):**
1521
+
1522
+ ```tsx
1523
+ function SearchResults() {
1524
+ const [query, setQuery] = useState('')
1525
+ const [results, setResults] = useState([])
1526
+ const [isLoading, setIsLoading] = useState(false)
1527
+
1528
+ const handleSearch = async (value: string) => {
1529
+ setIsLoading(true)
1530
+ setQuery(value)
1531
+ const data = await fetchResults(value)
1532
+ setResults(data)
1533
+ setIsLoading(false)
1534
+ }
1535
+
1536
+ return (
1537
+ <>
1538
+ <input onChange={(e) => handleSearch(e.target.value)} />
1539
+ {isLoading && <Spinner />}
1540
+ <ResultsList results={results} />
1541
+ </>
1542
+ )
1543
+ }
1544
+ ```
1545
+
1546
+ **Correct (useTransition with built-in pending state):**
1547
+
1548
+ ```tsx
1549
+ import { useTransition, useState } from 'react'
1550
+
1551
+ function SearchResults() {
1552
+ const [query, setQuery] = useState('')
1553
+ const [results, setResults] = useState([])
1554
+ const [isPending, startTransition] = useTransition()
1555
+
1556
+ const handleSearch = (value: string) => {
1557
+ setQuery(value) // Update input immediately
1558
+
1559
+ startTransition(async () => {
1560
+ // Fetch and update results
1561
+ const data = await fetchResults(value)
1562
+ setResults(data)
1563
+ })
1564
+ }
1565
+
1566
+ return (
1567
+ <>
1568
+ <input onChange={(e) => handleSearch(e.target.value)} />
1569
+ {isPending && <Spinner />}
1570
+ <ResultsList results={results} />
1571
+ </>
1572
+ )
1573
+ }
1574
+ ```
1575
+
1576
+ **Benefits:**
1577
+
1578
+ - **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
1579
+ - **Error resilience**: Pending state correctly resets even if the transition throws
1580
+ - **Better responsiveness**: Keeps the UI responsive during updates
1581
+ - **Interrupt handling**: New transitions automatically cancel pending ones
1582
+
1583
+ Reference: [useTransition](https://react.dev/reference/react/useTransition)
1584
+ ---
1585
+ title: Use Functional setState Updates
1586
+ impact: MEDIUM
1587
+ impactDescription: prevents stale closures and unnecessary callback recreations
1588
+ tags: react, hooks, useState, useCallback, callbacks, closures
1589
+ ---
1590
+
1591
+ ## Use Functional setState Updates
1592
+
1593
+ 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.
1594
+
1595
+ **Incorrect (requires state as dependency):**
1596
+
1597
+ ```tsx
1598
+ function TodoList() {
1599
+ const [items, setItems] = useState(initialItems)
1600
+
1601
+ // Callback must depend on items, recreated on every items change
1602
+ const addItems = useCallback((newItems: Item[]) => {
1603
+ setItems([...items, ...newItems])
1604
+ }, [items]) // ❌ items dependency causes recreations
1605
+
1606
+ // Risk of stale closure if dependency is forgotten
1607
+ const removeItem = useCallback((id: string) => {
1608
+ setItems(items.filter(item => item.id !== id))
1609
+ }, []) // ❌ Missing items dependency - will use stale items!
1610
+
1611
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
1612
+ }
1613
+ ```
1614
+
1615
+ 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.
1616
+
1617
+ **Correct (stable callbacks, no stale closures):**
1618
+
1619
+ ```tsx
1620
+ function TodoList() {
1621
+ const [items, setItems] = useState(initialItems)
1622
+
1623
+ // Stable callback, never recreated
1624
+ const addItems = useCallback((newItems: Item[]) => {
1625
+ setItems(curr => [...curr, ...newItems])
1626
+ }, []) // ✅ No dependencies needed
1627
+
1628
+ // Always uses latest state, no stale closure risk
1629
+ const removeItem = useCallback((id: string) => {
1630
+ setItems(curr => curr.filter(item => item.id !== id))
1631
+ }, []) // ✅ Safe and stable
1632
+
1633
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
1634
+ }
1635
+ ```
1636
+
1637
+ **Benefits:**
1638
+
1639
+ 1. **Stable callback references** - Callbacks don't need to be recreated when state changes
1640
+ 2. **No stale closures** - Always operates on the latest state value
1641
+ 3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
1642
+ 4. **Prevents bugs** - Eliminates the most common source of React closure bugs
1643
+
1644
+ **When to use functional updates:**
1645
+
1646
+ - Any setState that depends on the current state value
1647
+ - Inside useCallback/useMemo when state is needed
1648
+ - Event handlers that reference state
1649
+ - Async operations that update state
1650
+
1651
+ **When direct updates are fine:**
1652
+
1653
+ - Setting state to a static value: `setCount(0)`
1654
+ - Setting state from props/arguments only: `setName(newName)`
1655
+ - State doesn't depend on previous value
1656
+
1657
+ **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.
1658
+ ---
1659
+ title: Use Lazy State Initialization
1660
+ impact: MEDIUM
1661
+ impactDescription: wasted computation on every render
1662
+ tags: react, hooks, useState, performance, initialization
1663
+ ---
1664
+
1665
+ ## Use Lazy State Initialization
1666
+
1667
+ 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.
1668
+
1669
+ **Incorrect (runs on every render):**
1670
+
1671
+ ```tsx
1672
+ function FilteredList({ items }: { items: Item[] }) {
1673
+ // buildSearchIndex() runs on EVERY render, even after initialization
1674
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
1675
+ const [query, setQuery] = useState('')
1676
+
1677
+ // When query changes, buildSearchIndex runs again unnecessarily
1678
+ return <SearchResults index={searchIndex} query={query} />
1679
+ }
1680
+
1681
+ function UserProfile() {
1682
+ // JSON.parse runs on every render
1683
+ const [settings, setSettings] = useState(
1684
+ JSON.parse(localStorage.getItem('settings') || '{}')
1685
+ )
1686
+
1687
+ return <SettingsForm settings={settings} onChange={setSettings} />
1688
+ }
1689
+ ```
1690
+
1691
+ **Correct (runs only once):**
1692
+
1693
+ ```tsx
1694
+ function FilteredList({ items }: { items: Item[] }) {
1695
+ // buildSearchIndex() runs ONLY on initial render
1696
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
1697
+ const [query, setQuery] = useState('')
1698
+
1699
+ return <SearchResults index={searchIndex} query={query} />
1700
+ }
1701
+
1702
+ function UserProfile() {
1703
+ // JSON.parse runs only on initial render
1704
+ const [settings, setSettings] = useState(() => {
1705
+ const stored = localStorage.getItem('settings')
1706
+ return stored ? JSON.parse(stored) : {}
1707
+ })
1708
+
1709
+ return <SettingsForm settings={settings} onChange={setSettings} />
1710
+ }
1711
+ ```
1712
+
1713
+ Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
1714
+
1715
+ For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
1716
+ ---
1717
+ title: Store Event Handlers in Refs
1718
+ impact: LOW
1719
+ impactDescription: stable subscriptions
1720
+ tags: advanced, hooks, refs, event-handlers, optimization
1721
+ ---
1722
+
1723
+ ## Store Event Handlers in Refs
1724
+
1725
+ Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
1726
+
1727
+ **Incorrect (re-subscribes on every render):**
1728
+
1729
+ ```tsx
1730
+ function useWindowEvent(event: string, handler: (e) => void) {
1731
+ useEffect(() => {
1732
+ window.addEventListener(event, handler)
1733
+ return () => window.removeEventListener(event, handler)
1734
+ }, [event, handler])
1735
+ }
1736
+ ```
1737
+
1738
+ **Correct (stable subscription):**
1739
+
1740
+ ```tsx
1741
+ function useWindowEvent(event: string, handler: (e) => void) {
1742
+ const handlerRef = useRef(handler)
1743
+ useEffect(() => {
1744
+ handlerRef.current = handler
1745
+ }, [handler])
1746
+
1747
+ useEffect(() => {
1748
+ const listener = (e) => handlerRef.current(e)
1749
+ window.addEventListener(event, listener)
1750
+ return () => window.removeEventListener(event, listener)
1751
+ }, [event])
1752
+ }
1753
+ ```
1754
+
1755
+ **Alternative: use `useEffectEvent` if you're on latest React:**
1756
+
1757
+ ```tsx
1758
+ import { useEffectEvent } from 'react'
1759
+
1760
+ function useWindowEvent(event: string, handler: (e) => void) {
1761
+ const onEvent = useEffectEvent(handler)
1762
+
1763
+ useEffect(() => {
1764
+ window.addEventListener(event, onEvent)
1765
+ return () => window.removeEventListener(event, onEvent)
1766
+ }, [event])
1767
+ }
1768
+ ```
1769
+
1770
+ `useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
1771
+ ---
1772
+ title: Use after() for Non-Blocking Operations
1773
+ impact: MEDIUM
1774
+ impactDescription: faster response times
1775
+ tags: server, async, logging, analytics, side-effects
1776
+ ---
1777
+
1778
+ ## Use after() for Non-Blocking Operations
1779
+
1780
+ 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.
1781
+
1782
+ **Incorrect (blocks response):**
1783
+
1784
+ ```tsx
1785
+ import { logUserAction } from '@/app/utils'
1786
+
1787
+ export async function POST(request: Request) {
1788
+ // Perform mutation
1789
+ await updateDatabase(request)
1790
+
1791
+ // Logging blocks the response
1792
+ const userAgent = request.headers.get('user-agent') || 'unknown'
1793
+ await logUserAction({ userAgent })
1794
+
1795
+ return new Response(JSON.stringify({ status: 'success' }), {
1796
+ status: 200,
1797
+ headers: { 'Content-Type': 'application/json' }
1798
+ })
1799
+ }
1800
+ ```
1801
+
1802
+ **Correct (non-blocking):**
1803
+
1804
+ ```tsx
1805
+ import { after } from 'next/server'
1806
+ import { headers, cookies } from 'next/headers'
1807
+ import { logUserAction } from '@/app/utils'
1808
+
1809
+ export async function POST(request: Request) {
1810
+ // Perform mutation
1811
+ await updateDatabase(request)
1812
+
1813
+ // Log after response is sent
1814
+ after(async () => {
1815
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
1816
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
1817
+
1818
+ logUserAction({ sessionCookie, userAgent })
1819
+ })
1820
+
1821
+ return new Response(JSON.stringify({ status: 'success' }), {
1822
+ status: 200,
1823
+ headers: { 'Content-Type': 'application/json' }
1824
+ })
1825
+ }
1826
+ ```
1827
+
1828
+ The response is sent immediately while logging happens in the background.
1829
+
1830
+ **Common use cases:**
1831
+
1832
+ - Analytics tracking
1833
+ - Audit logging
1834
+ - Sending notifications
1835
+ - Cache invalidation
1836
+ - Cleanup tasks
1837
+
1838
+ **Important notes:**
1839
+
1840
+ - `after()` runs even if the response fails or redirects
1841
+ - Works in Server Actions, Route Handlers, and Server Components
1842
+
1843
+ Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
1844
+ ---
1845
+ title: Deduplicate Global Event Listeners
1846
+ impact: LOW
1847
+ impactDescription: single listener for N components
1848
+ tags: client, swr, event-listeners, subscription
1849
+ ---
1850
+
1851
+ ## Deduplicate Global Event Listeners
1852
+
1853
+ Use `useSWRSubscription()` to share global event listeners across component instances.
1854
+
1855
+ **Incorrect (N instances = N listeners):**
1856
+
1857
+ ```tsx
1858
+ function useKeyboardShortcut(key: string, callback: () => void) {
1859
+ useEffect(() => {
1860
+ const handler = (e: KeyboardEvent) => {
1861
+ if (e.metaKey && e.key === key) {
1862
+ callback()
1863
+ }
1864
+ }
1865
+ window.addEventListener('keydown', handler)
1866
+ return () => window.removeEventListener('keydown', handler)
1867
+ }, [key, callback])
1868
+ }
1869
+ ```
1870
+
1871
+ When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
1872
+
1873
+ **Correct (N instances = 1 listener):**
1874
+
1875
+ ```tsx
1876
+ import useSWRSubscription from 'swr/subscription'
1877
+
1878
+ // Module-level Map to track callbacks per key
1879
+ const keyCallbacks = new Map<string, Set<() => void>>()
1880
+
1881
+ function useKeyboardShortcut(key: string, callback: () => void) {
1882
+ // Register this callback in the Map
1883
+ useEffect(() => {
1884
+ if (!keyCallbacks.has(key)) {
1885
+ keyCallbacks.set(key, new Set())
1886
+ }
1887
+ keyCallbacks.get(key)!.add(callback)
1888
+
1889
+ return () => {
1890
+ const set = keyCallbacks.get(key)
1891
+ if (set) {
1892
+ set.delete(callback)
1893
+ if (set.size === 0) {
1894
+ keyCallbacks.delete(key)
1895
+ }
1896
+ }
1897
+ }
1898
+ }, [key, callback])
1899
+
1900
+ useSWRSubscription('global-keydown', () => {
1901
+ const handler = (e: KeyboardEvent) => {
1902
+ if (e.metaKey && keyCallbacks.has(e.key)) {
1903
+ keyCallbacks.get(e.key)!.forEach(cb => cb())
1904
+ }
1905
+ }
1906
+ window.addEventListener('keydown', handler)
1907
+ return () => window.removeEventListener('keydown', handler)
1908
+ })
1909
+ }
1910
+
1911
+ function Profile() {
1912
+ // Multiple shortcuts will share the same listener
1913
+ useKeyboardShortcut('p', () => { /* ... */ })
1914
+ useKeyboardShortcut('k', () => { /* ... */ })
1915
+ // ...
1916
+ }
1917
+ ```
1918
+ ---
1919
+ title: Use Transitions for Non-Urgent Updates
1920
+ impact: MEDIUM
1921
+ impactDescription: maintains UI responsiveness
1922
+ tags: rerender, transitions, startTransition, performance
1923
+ ---
1924
+
1925
+ ## Use Transitions for Non-Urgent Updates
1926
+
1927
+ Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
1928
+
1929
+ **Incorrect (blocks UI on every scroll):**
1930
+
1931
+ ```tsx
1932
+ function ScrollTracker() {
1933
+ const [scrollY, setScrollY] = useState(0)
1934
+ useEffect(() => {
1935
+ const handler = () => setScrollY(window.scrollY)
1936
+ window.addEventListener('scroll', handler, { passive: true })
1937
+ return () => window.removeEventListener('scroll', handler)
1938
+ }, [])
1939
+ }
1940
+ ```
1941
+
1942
+ **Correct (non-blocking updates):**
1943
+
1944
+ ```tsx
1945
+ import { startTransition } from 'react'
1946
+
1947
+ function ScrollTracker() {
1948
+ const [scrollY, setScrollY] = useState(0)
1949
+ useEffect(() => {
1950
+ const handler = () => {
1951
+ startTransition(() => setScrollY(window.scrollY))
1952
+ }
1953
+ window.addEventListener('scroll', handler, { passive: true })
1954
+ return () => window.removeEventListener('scroll', handler)
1955
+ }, [])
1956
+ }
1957
+ ```
1958
+ ---
1959
+ title: Use toSorted() Instead of sort() for Immutability
1960
+ impact: MEDIUM-HIGH
1961
+ impactDescription: prevents mutation bugs in React state
1962
+ tags: javascript, arrays, immutability, react, state, mutation
1963
+ ---
1964
+
1965
+ ## Use toSorted() Instead of sort() for Immutability
1966
+
1967
+ `.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.
1968
+
1969
+ **Incorrect (mutates original array):**
1970
+
1971
+ ```typescript
1972
+ function UserList({ users }: { users: User[] }) {
1973
+ // Mutates the users prop array!
1974
+ const sorted = useMemo(
1975
+ () => users.sort((a, b) => a.name.localeCompare(b.name)),
1976
+ [users]
1977
+ )
1978
+ return <div>{sorted.map(renderUser)}</div>
1979
+ }
1980
+ ```
1981
+
1982
+ **Correct (creates new array):**
1983
+
1984
+ ```typescript
1985
+ function UserList({ users }: { users: User[] }) {
1986
+ // Creates new sorted array, original unchanged
1987
+ const sorted = useMemo(
1988
+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
1989
+ [users]
1990
+ )
1991
+ return <div>{sorted.map(renderUser)}</div>
1992
+ }
1993
+ ```
1994
+
1995
+ **Why this matters in React:**
1996
+
1997
+ 1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
1998
+ 2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
1999
+
2000
+ **Browser support (fallback for older browsers):**
2001
+
2002
+ `.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
2003
+
2004
+ ```typescript
2005
+ // Fallback for older browsers
2006
+ const sorted = [...items].sort((a, b) => a.value - b.value)
2007
+ ```
2008
+
2009
+ **Other immutable array methods:**
2010
+
2011
+ - `.toSorted()` - immutable sort
2012
+ - `.toReversed()` - immutable reverse
2013
+ - `.toSpliced()` - immutable splice
2014
+ - `.with()` - immutable element replacement
2015
+ ---
2016
+ title: Use SWR for Automatic Deduplication
2017
+ impact: MEDIUM-HIGH
2018
+ impactDescription: automatic deduplication
2019
+ tags: client, swr, deduplication, data-fetching
2020
+ ---
2021
+
2022
+ ## Use SWR for Automatic Deduplication
2023
+
2024
+ SWR enables request deduplication, caching, and revalidation across component instances.
2025
+
2026
+ **Incorrect (no deduplication, each instance fetches):**
2027
+
2028
+ ```tsx
2029
+ function UserList() {
2030
+ const [users, setUsers] = useState([])
2031
+ useEffect(() => {
2032
+ fetch('/api/users')
2033
+ .then(r => r.json())
2034
+ .then(setUsers)
2035
+ }, [])
2036
+ }
2037
+ ```
2038
+
2039
+ **Correct (multiple instances share one request):**
2040
+
2041
+ ```tsx
2042
+ import useSWR from 'swr'
2043
+
2044
+ function UserList() {
2045
+ const { data: users } = useSWR('/api/users', fetcher)
2046
+ }
2047
+ ```
2048
+
2049
+ **For immutable data:**
2050
+
2051
+ ```tsx
2052
+ import { useImmutableSWR } from '@/lib/swr'
2053
+
2054
+ function StaticContent() {
2055
+ const { data } = useImmutableSWR('/api/config', fetcher)
2056
+ }
2057
+ ```
2058
+
2059
+ **For mutations:**
2060
+
2061
+ ```tsx
2062
+ import { useSWRMutation } from 'swr/mutation'
2063
+
2064
+ function UpdateButton() {
2065
+ const { trigger } = useSWRMutation('/api/user', updateUser)
2066
+ return <button onClick={() => trigger()}>Update</button>
2067
+ }
2068
+ ```
2069
+
2070
+ Reference: [https://swr.vercel.app](https://swr.vercel.app)
2071
+ ---
2072
+ title: Per-Request Deduplication with React.cache()
2073
+ impact: MEDIUM
2074
+ impactDescription: deduplicates within request
2075
+ tags: server, cache, react-cache, deduplication
2076
+ ---
2077
+
2078
+ ## Per-Request Deduplication with React.cache()
2079
+
2080
+ Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
2081
+
2082
+ **Usage:**
2083
+
2084
+ ```typescript
2085
+ import { cache } from 'react'
2086
+
2087
+ export const getCurrentUser = cache(async () => {
2088
+ const session = await auth()
2089
+ if (!session?.user?.id) return null
2090
+ return await db.user.findUnique({
2091
+ where: { id: session.user.id }
2092
+ })
2093
+ })
2094
+ ```
2095
+
2096
+ Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
2097
+
2098
+ **Avoid inline objects as arguments:**
2099
+
2100
+ `React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
2101
+
2102
+ **Incorrect (always cache miss):**
2103
+
2104
+ ```typescript
2105
+ const getUser = cache(async (params: { uid: number }) => {
2106
+ return await db.user.findUnique({ where: { id: params.uid } })
2107
+ })
2108
+
2109
+ // Each call creates new object, never hits cache
2110
+ getUser({ uid: 1 })
2111
+ getUser({ uid: 1 }) // Cache miss, runs query again
2112
+ ```
2113
+
2114
+ **Correct (cache hit):**
2115
+
2116
+ ```typescript
2117
+ const getUser = cache(async (uid: number) => {
2118
+ return await db.user.findUnique({ where: { id: uid } })
2119
+ })
2120
+
2121
+ // Primitive args use value equality
2122
+ getUser(1)
2123
+ getUser(1) // Cache hit, returns cached result
2124
+ ```
2125
+
2126
+ If you must pass objects, pass the same reference:
2127
+
2128
+ ```typescript
2129
+ const params = { uid: 1 }
2130
+ getUser(params) // Query runs
2131
+ getUser(params) // Cache hit (same reference)
2132
+ ```
2133
+
2134
+ **Next.js-Specific Note:**
2135
+
2136
+ 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:
2137
+
2138
+ - Database queries (Prisma, Drizzle, etc.)
2139
+ - Heavy computations
2140
+ - Authentication checks
2141
+ - File system operations
2142
+ - Any non-fetch async work
2143
+
2144
+ Use `React.cache()` to deduplicate these operations across your component tree.
2145
+
2146
+ Reference: [React.cache documentation](https://react.dev/reference/react/cache)
2147
+ ---
2148
+ title: Dynamic Imports for Heavy Components
2149
+ impact: CRITICAL
2150
+ impactDescription: directly affects TTI and LCP
2151
+ tags: bundle, dynamic-import, code-splitting, next-dynamic
2152
+ ---
2153
+
2154
+ ## Dynamic Imports for Heavy Components
2155
+
2156
+ Use `next/dynamic` to lazy-load large components not needed on initial render.
2157
+
2158
+ **Incorrect (Monaco bundles with main chunk ~300KB):**
2159
+
2160
+ ```tsx
2161
+ import { MonacoEditor } from './monaco-editor'
2162
+
2163
+ function CodePanel({ code }: { code: string }) {
2164
+ return <MonacoEditor value={code} />
2165
+ }
2166
+ ```
2167
+
2168
+ **Correct (Monaco loads on demand):**
2169
+
2170
+ ```tsx
2171
+ import dynamic from 'next/dynamic'
2172
+
2173
+ const MonacoEditor = dynamic(
2174
+ () => import('./monaco-editor').then(m => m.MonacoEditor),
2175
+ { ssr: false }
2176
+ )
2177
+
2178
+ function CodePanel({ code }: { code: string }) {
2179
+ return <MonacoEditor value={code} />
2180
+ }
2181
+ ```
2182
+ ---
2183
+ title: Prevent Hydration Mismatch Without Flickering
2184
+ impact: MEDIUM
2185
+ impactDescription: avoids visual flicker and hydration errors
2186
+ tags: rendering, ssr, hydration, localStorage, flicker
2187
+ ---
2188
+
2189
+ ## Prevent Hydration Mismatch Without Flickering
2190
+
2191
+ 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.
2192
+
2193
+ **Incorrect (breaks SSR):**
2194
+
2195
+ ```tsx
2196
+ function ThemeWrapper({ children }: { children: ReactNode }) {
2197
+ // localStorage is not available on server - throws error
2198
+ const theme = localStorage.getItem('theme') || 'light'
2199
+
2200
+ return (
2201
+ <div className={theme}>
2202
+ {children}
2203
+ </div>
2204
+ )
2205
+ }
2206
+ ```
2207
+
2208
+ Server-side rendering will fail because `localStorage` is undefined.
2209
+
2210
+ **Incorrect (visual flickering):**
2211
+
2212
+ ```tsx
2213
+ function ThemeWrapper({ children }: { children: ReactNode }) {
2214
+ const [theme, setTheme] = useState('light')
2215
+
2216
+ useEffect(() => {
2217
+ // Runs after hydration - causes visible flash
2218
+ const stored = localStorage.getItem('theme')
2219
+ if (stored) {
2220
+ setTheme(stored)
2221
+ }
2222
+ }, [])
2223
+
2224
+ return (
2225
+ <div className={theme}>
2226
+ {children}
2227
+ </div>
2228
+ )
2229
+ }
2230
+ ```
2231
+
2232
+ Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
2233
+
2234
+ **Correct (no flicker, no hydration mismatch):**
2235
+
2236
+ ```tsx
2237
+ function ThemeWrapper({ children }: { children: ReactNode }) {
2238
+ return (
2239
+ <>
2240
+ <div id="theme-wrapper">
2241
+ {children}
2242
+ </div>
2243
+ <script
2244
+ dangerouslySetInnerHTML={{
2245
+ __html: `
2246
+ (function() {
2247
+ try {
2248
+ var theme = localStorage.getItem('theme') || 'light';
2249
+ var el = document.getElementById('theme-wrapper');
2250
+ if (el) el.className = theme;
2251
+ } catch (e) {}
2252
+ })();
2253
+ `,
2254
+ }}
2255
+ />
2256
+ </>
2257
+ )
2258
+ }
2259
+ ```
2260
+
2261
+ The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
2262
+
2263
+ 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.
2264
+ ---
2265
+ title: Minimize Serialization at RSC Boundaries
2266
+ impact: HIGH
2267
+ impactDescription: reduces data transfer size
2268
+ tags: server, rsc, serialization, props
2269
+ ---
2270
+
2271
+ ## Minimize Serialization at RSC Boundaries
2272
+
2273
+ 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.
2274
+
2275
+ **Incorrect (serializes all 50 fields):**
2276
+
2277
+ ```tsx
2278
+ async function Page() {
2279
+ const user = await fetchUser() // 50 fields
2280
+ return <Profile user={user} />
2281
+ }
2282
+
2283
+ 'use client'
2284
+ function Profile({ user }: { user: User }) {
2285
+ return <div>{user.name}</div> // uses 1 field
2286
+ }
2287
+ ```
2288
+
2289
+ **Correct (serializes only 1 field):**
2290
+
2291
+ ```tsx
2292
+ async function Page() {
2293
+ const user = await fetchUser()
2294
+ return <Profile name={user.name} />
2295
+ }
2296
+
2297
+ 'use client'
2298
+ function Profile({ name }: { name: string }) {
2299
+ return <div>{name}</div>
2300
+ }
2301
+ ```
2302
+ ---
2303
+ title: Optimize SVG Precision
2304
+ impact: LOW
2305
+ impactDescription: reduces file size
2306
+ tags: rendering, svg, optimization, svgo
2307
+ ---
2308
+
2309
+ ## Optimize SVG Precision
2310
+
2311
+ Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
2312
+
2313
+ **Incorrect (excessive precision):**
2314
+
2315
+ ```svg
2316
+ <path d="M 10.293847 20.847362 L 30.938472 40.192837" />
2317
+ ```
2318
+
2319
+ **Correct (1 decimal place):**
2320
+
2321
+ ```svg
2322
+ <path d="M 10.3 20.8 L 30.9 40.2" />
2323
+ ```
2324
+
2325
+ **Automate with SVGO:**
2326
+
2327
+ ```bash
2328
+ npx svgo --precision=1 --multipass icon.svg
2329
+ ```
2330
+ ---
2331
+ title: Extract to Memoized Components
2332
+ impact: MEDIUM
2333
+ impactDescription: enables early returns
2334
+ tags: rerender, memo, useMemo, optimization
2335
+ ---
2336
+
2337
+ ## Extract to Memoized Components
2338
+
2339
+ Extract expensive work into memoized components to enable early returns before computation.
2340
+
2341
+ **Incorrect (computes avatar even when loading):**
2342
+
2343
+ ```tsx
2344
+ function Profile({ user, loading }: Props) {
2345
+ const avatar = useMemo(() => {
2346
+ const id = computeAvatarId(user)
2347
+ return <Avatar id={id} />
2348
+ }, [user])
2349
+
2350
+ if (loading) return <Skeleton />
2351
+ return <div>{avatar}</div>
2352
+ }
2353
+ ```
2354
+
2355
+ **Correct (skips computation when loading):**
2356
+
2357
+ ```tsx
2358
+ const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
2359
+ const id = useMemo(() => computeAvatarId(user), [user])
2360
+ return <Avatar id={id} />
2361
+ })
2362
+
2363
+ function Profile({ user, loading }: Props) {
2364
+ if (loading) return <Skeleton />
2365
+ return (
2366
+ <div>
2367
+ <UserAvatar user={user} />
2368
+ </div>
2369
+ )
2370
+ }
2371
+ ```
2372
+
2373
+ **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.
2374
+ ---
2375
+ title: Initialize App Once, Not Per Mount
2376
+ impact: LOW-MEDIUM
2377
+ impactDescription: avoids duplicate init in development
2378
+ tags: initialization, useEffect, app-startup, side-effects
2379
+ ---
2380
+
2381
+ ## Initialize App Once, Not Per Mount
2382
+
2383
+ Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
2384
+
2385
+ **Incorrect (runs twice in dev, re-runs on remount):**
2386
+
2387
+ ```tsx
2388
+ function Comp() {
2389
+ useEffect(() => {
2390
+ loadFromStorage()
2391
+ checkAuthToken()
2392
+ }, [])
2393
+
2394
+ // ...
2395
+ }
2396
+ ```
2397
+
2398
+ **Correct (once per app load):**
2399
+
2400
+ ```tsx
2401
+ let didInit = false
2402
+
2403
+ function Comp() {
2404
+ useEffect(() => {
2405
+ if (didInit) return
2406
+ didInit = true
2407
+ loadFromStorage()
2408
+ checkAuthToken()
2409
+ }, [])
2410
+
2411
+ // ...
2412
+ }
2413
+ ```
2414
+
2415
+ Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
2416
+ ---
2417
+ title: CSS content-visibility for Long Lists
2418
+ impact: HIGH
2419
+ impactDescription: faster initial render
2420
+ tags: rendering, css, content-visibility, long-lists
2421
+ ---
2422
+
2423
+ ## CSS content-visibility for Long Lists
2424
+
2425
+ Apply `content-visibility: auto` to defer off-screen rendering.
2426
+
2427
+ **CSS:**
2428
+
2429
+ ```css
2430
+ .message-item {
2431
+ content-visibility: auto;
2432
+ contain-intrinsic-size: 0 80px;
2433
+ }
2434
+ ```
2435
+
2436
+ **Example:**
2437
+
2438
+ ```tsx
2439
+ function MessageList({ messages }: { messages: Message[] }) {
2440
+ return (
2441
+ <div className="overflow-y-auto h-screen">
2442
+ {messages.map(msg => (
2443
+ <div key={msg.id} className="message-item">
2444
+ <Avatar user={msg.author} />
2445
+ <div>{msg.content}</div>
2446
+ </div>
2447
+ ))}
2448
+ </div>
2449
+ )
2450
+ }
2451
+ ```
2452
+
2453
+ For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
2454
+ ---
2455
+ title: Promise.all() for Independent Operations
2456
+ impact: CRITICAL
2457
+ impactDescription: 2-10× improvement
2458
+ tags: async, parallelization, promises, waterfalls
2459
+ ---
2460
+
2461
+ ## Promise.all() for Independent Operations
2462
+
2463
+ When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
2464
+
2465
+ **Incorrect (sequential execution, 3 round trips):**
2466
+
2467
+ ```typescript
2468
+ const user = await fetchUser()
2469
+ const posts = await fetchPosts()
2470
+ const comments = await fetchComments()
2471
+ ```
2472
+
2473
+ **Correct (parallel execution, 1 round trip):**
2474
+
2475
+ ```typescript
2476
+ const [user, posts, comments] = await Promise.all([
2477
+ fetchUser(),
2478
+ fetchPosts(),
2479
+ fetchComments()
2480
+ ])
2481
+ ```
2482
+ ---
2483
+ title: Avoid Layout Thrashing
2484
+ impact: MEDIUM
2485
+ impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
2486
+ tags: javascript, dom, css, performance, reflow, layout-thrashing
2487
+ ---
2488
+
2489
+ ## Avoid Layout Thrashing
2490
+
2491
+ 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.
2492
+
2493
+ **This is OK (browser batches style changes):**
2494
+ ```typescript
2495
+ function updateElementStyles(element: HTMLElement) {
2496
+ // Each line invalidates style, but browser batches the recalculation
2497
+ element.style.width = '100px'
2498
+ element.style.height = '200px'
2499
+ element.style.backgroundColor = 'blue'
2500
+ element.style.border = '1px solid black'
2501
+ }
2502
+ ```
2503
+
2504
+ **Incorrect (interleaved reads and writes force reflows):**
2505
+ ```typescript
2506
+ function layoutThrashing(element: HTMLElement) {
2507
+ element.style.width = '100px'
2508
+ const width = element.offsetWidth // Forces reflow
2509
+ element.style.height = '200px'
2510
+ const height = element.offsetHeight // Forces another reflow
2511
+ }
2512
+ ```
2513
+
2514
+ **Correct (batch writes, then read once):**
2515
+ ```typescript
2516
+ function updateElementStyles(element: HTMLElement) {
2517
+ // Batch all writes together
2518
+ element.style.width = '100px'
2519
+ element.style.height = '200px'
2520
+ element.style.backgroundColor = 'blue'
2521
+ element.style.border = '1px solid black'
2522
+
2523
+ // Read after all writes are done (single reflow)
2524
+ const { width, height } = element.getBoundingClientRect()
2525
+ }
2526
+ ```
2527
+
2528
+ **Correct (batch reads, then writes):**
2529
+ ```typescript
2530
+ function avoidThrashing(element: HTMLElement) {
2531
+ // Read phase - all layout queries first
2532
+ const rect1 = element.getBoundingClientRect()
2533
+ const offsetWidth = element.offsetWidth
2534
+ const offsetHeight = element.offsetHeight
2535
+
2536
+ // Write phase - all style changes after
2537
+ element.style.width = '100px'
2538
+ element.style.height = '200px'
2539
+ }
2540
+ ```
2541
+
2542
+ **Better: use CSS classes**
2543
+ ```css
2544
+ .highlighted-box {
2545
+ width: 100px;
2546
+ height: 200px;
2547
+ background-color: blue;
2548
+ border: 1px solid black;
2549
+ }
2550
+ ```
2551
+ ```typescript
2552
+ function updateElementStyles(element: HTMLElement) {
2553
+ element.classList.add('highlighted-box')
2554
+
2555
+ const { width, height } = element.getBoundingClientRect()
2556
+ }
2557
+ ```
2558
+
2559
+ **React example:**
2560
+ ```tsx
2561
+ // Incorrect: interleaving style changes with layout queries
2562
+ function Box({ isHighlighted }: { isHighlighted: boolean }) {
2563
+ const ref = useRef<HTMLDivElement>(null)
2564
+
2565
+ useEffect(() => {
2566
+ if (ref.current && isHighlighted) {
2567
+ ref.current.style.width = '100px'
2568
+ const width = ref.current.offsetWidth // Forces layout
2569
+ ref.current.style.height = '200px'
2570
+ }
2571
+ }, [isHighlighted])
2572
+
2573
+ return <div ref={ref}>Content</div>
2574
+ }
2575
+
2576
+ // Correct: toggle class
2577
+ function Box({ isHighlighted }: { isHighlighted: boolean }) {
2578
+ return (
2579
+ <div className={isHighlighted ? 'highlighted-box' : ''}>
2580
+ Content
2581
+ </div>
2582
+ )
2583
+ }
2584
+ ```
2585
+
2586
+ 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.
2587
+
2588
+ See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
2589
+ ---
2590
+ title: Authenticate Server Actions Like API Routes
2591
+ impact: CRITICAL
2592
+ impactDescription: prevents unauthorized access to server mutations
2593
+ tags: server, server-actions, authentication, security, authorization
2594
+ ---
2595
+
2596
+ ## Authenticate Server Actions Like API Routes
2597
+
2598
+ **Impact: CRITICAL (prevents unauthorized access to server mutations)**
2599
+
2600
+ 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.
2601
+
2602
+ 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."
2603
+
2604
+ **Incorrect (no authentication check):**
2605
+
2606
+ ```typescript
2607
+ 'use server'
2608
+
2609
+ export async function deleteUser(userId: string) {
2610
+ // Anyone can call this! No auth check
2611
+ await db.user.delete({ where: { id: userId } })
2612
+ return { success: true }
2613
+ }
2614
+ ```
2615
+
2616
+ **Correct (authentication inside the action):**
2617
+
2618
+ ```typescript
2619
+ 'use server'
2620
+
2621
+ import { verifySession } from '@/lib/auth'
2622
+ import { unauthorized } from '@/lib/errors'
2623
+
2624
+ export async function deleteUser(userId: string) {
2625
+ // Always check auth inside the action
2626
+ const session = await verifySession()
2627
+
2628
+ if (!session) {
2629
+ throw unauthorized('Must be logged in')
2630
+ }
2631
+
2632
+ // Check authorization too
2633
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
2634
+ throw unauthorized('Cannot delete other users')
2635
+ }
2636
+
2637
+ await db.user.delete({ where: { id: userId } })
2638
+ return { success: true }
2639
+ }
2640
+ ```
2641
+
2642
+ **With input validation:**
2643
+
2644
+ ```typescript
2645
+ 'use server'
2646
+
2647
+ import { verifySession } from '@/lib/auth'
2648
+ import { z } from 'zod'
2649
+
2650
+ const updateProfileSchema = z.object({
2651
+ userId: z.string().uuid(),
2652
+ name: z.string().min(1).max(100),
2653
+ email: z.string().email()
2654
+ })
2655
+
2656
+ export async function updateProfile(data: unknown) {
2657
+ // Validate input first
2658
+ const validated = updateProfileSchema.parse(data)
2659
+
2660
+ // Then authenticate
2661
+ const session = await verifySession()
2662
+ if (!session) {
2663
+ throw new Error('Unauthorized')
2664
+ }
2665
+
2666
+ // Then authorize
2667
+ if (session.user.id !== validated.userId) {
2668
+ throw new Error('Can only update own profile')
2669
+ }
2670
+
2671
+ // Finally perform the mutation
2672
+ await db.user.update({
2673
+ where: { id: validated.userId },
2674
+ data: {
2675
+ name: validated.name,
2676
+ email: validated.email
2677
+ }
2678
+ })
2679
+
2680
+ return { success: true }
2681
+ }
2682
+ ```
2683
+
2684
+ Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
2685
+ ---
2686
+ title: Cache Repeated Function Calls
2687
+ impact: MEDIUM
2688
+ impactDescription: avoid redundant computation
2689
+ tags: javascript, cache, memoization, performance
2690
+ ---
2691
+
2692
+ ## Cache Repeated Function Calls
2693
+
2694
+ Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
2695
+
2696
+ **Incorrect (redundant computation):**
2697
+
2698
+ ```typescript
2699
+ function ProjectList({ projects }: { projects: Project[] }) {
2700
+ return (
2701
+ <div>
2702
+ {projects.map(project => {
2703
+ // slugify() called 100+ times for same project names
2704
+ const slug = slugify(project.name)
2705
+
2706
+ return <ProjectCard key={project.id} slug={slug} />
2707
+ })}
2708
+ </div>
2709
+ )
2710
+ }
2711
+ ```
2712
+
2713
+ **Correct (cached results):**
2714
+
2715
+ ```typescript
2716
+ // Module-level cache
2717
+ const slugifyCache = new Map<string, string>()
2718
+
2719
+ function cachedSlugify(text: string): string {
2720
+ if (slugifyCache.has(text)) {
2721
+ return slugifyCache.get(text)!
2722
+ }
2723
+ const result = slugify(text)
2724
+ slugifyCache.set(text, result)
2725
+ return result
2726
+ }
2727
+
2728
+ function ProjectList({ projects }: { projects: Project[] }) {
2729
+ return (
2730
+ <div>
2731
+ {projects.map(project => {
2732
+ // Computed only once per unique project name
2733
+ const slug = cachedSlugify(project.name)
2734
+
2735
+ return <ProjectCard key={project.id} slug={slug} />
2736
+ })}
2737
+ </div>
2738
+ )
2739
+ }
2740
+ ```
2741
+
2742
+ **Simpler pattern for single-value functions:**
2743
+
2744
+ ```typescript
2745
+ let isLoggedInCache: boolean | null = null
2746
+
2747
+ function isLoggedIn(): boolean {
2748
+ if (isLoggedInCache !== null) {
2749
+ return isLoggedInCache
2750
+ }
2751
+
2752
+ isLoggedInCache = document.cookie.includes('auth=')
2753
+ return isLoggedInCache
2754
+ }
2755
+
2756
+ // Clear cache when auth changes
2757
+ function onAuthChange() {
2758
+ isLoggedInCache = null
2759
+ }
2760
+ ```
2761
+
2762
+ Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
2763
+
2764
+ Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
2765
+ ---
2766
+ title: Hoist RegExp Creation
2767
+ impact: LOW-MEDIUM
2768
+ impactDescription: avoids recreation
2769
+ tags: javascript, regexp, optimization, memoization
2770
+ ---
2771
+
2772
+ ## Hoist RegExp Creation
2773
+
2774
+ Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
2775
+
2776
+ **Incorrect (new RegExp every render):**
2777
+
2778
+ ```tsx
2779
+ function Highlighter({ text, query }: Props) {
2780
+ const regex = new RegExp(`(${query})`, 'gi')
2781
+ const parts = text.split(regex)
2782
+ return <>{parts.map((part, i) => ...)}</>
2783
+ }
2784
+ ```
2785
+
2786
+ **Correct (memoize or hoist):**
2787
+
2788
+ ```tsx
2789
+ const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
2790
+
2791
+ function Highlighter({ text, query }: Props) {
2792
+ const regex = useMemo(
2793
+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
2794
+ [query]
2795
+ )
2796
+ const parts = text.split(regex)
2797
+ return <>{parts.map((part, i) => ...)}</>
2798
+ }
2799
+ ```
2800
+
2801
+ **Warning (global regex has mutable state):**
2802
+
2803
+ Global regex (`/g`) has mutable `lastIndex` state:
2804
+
2805
+ ```typescript
2806
+ const regex = /foo/g
2807
+ regex.test('foo') // true, lastIndex = 3
2808
+ regex.test('foo') // false, lastIndex = 0
2809
+ ```
2810
+ ---
2811
+ title: Use Explicit Conditional Rendering
2812
+ impact: LOW
2813
+ impactDescription: prevents rendering 0 or NaN
2814
+ tags: rendering, conditional, jsx, falsy-values
2815
+ ---
2816
+
2817
+ ## Use Explicit Conditional Rendering
2818
+
2819
+ Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
2820
+
2821
+ **Incorrect (renders "0" when count is 0):**
2822
+
2823
+ ```tsx
2824
+ function Badge({ count }: { count: number }) {
2825
+ return (
2826
+ <div>
2827
+ {count && <span className="badge">{count}</span>}
2828
+ </div>
2829
+ )
2830
+ }
2831
+
2832
+ // When count = 0, renders: <div>0</div>
2833
+ // When count = 5, renders: <div><span class="badge">5</span></div>
2834
+ ```
2835
+
2836
+ **Correct (renders nothing when count is 0):**
2837
+
2838
+ ```tsx
2839
+ function Badge({ count }: { count: number }) {
2840
+ return (
2841
+ <div>
2842
+ {count > 0 ? <span className="badge">{count}</span> : null}
2843
+ </div>
2844
+ )
2845
+ }
2846
+
2847
+ // When count = 0, renders: <div></div>
2848
+ // When count = 5, renders: <div><span class="badge">5</span></div>
2849
+ ```
2850
+ ---
2851
+ title: Version and Minimize localStorage Data
2852
+ impact: MEDIUM
2853
+ impactDescription: prevents schema conflicts, reduces storage size
2854
+ tags: client, localStorage, storage, versioning, data-minimization
2855
+ ---
2856
+
2857
+ ## Version and Minimize localStorage Data
2858
+
2859
+ Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
2860
+
2861
+ **Incorrect:**
2862
+
2863
+ ```typescript
2864
+ // No version, stores everything, no error handling
2865
+ localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
2866
+ const data = localStorage.getItem('userConfig')
2867
+ ```
2868
+
2869
+ **Correct:**
2870
+
2871
+ ```typescript
2872
+ const VERSION = 'v2'
2873
+
2874
+ function saveConfig(config: { theme: string; language: string }) {
2875
+ try {
2876
+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
2877
+ } catch {
2878
+ // Throws in incognito/private browsing, quota exceeded, or disabled
2879
+ }
2880
+ }
2881
+
2882
+ function loadConfig() {
2883
+ try {
2884
+ const data = localStorage.getItem(`userConfig:${VERSION}`)
2885
+ return data ? JSON.parse(data) : null
2886
+ } catch {
2887
+ return null
2888
+ }
2889
+ }
2890
+
2891
+ // Migration from v1 to v2
2892
+ function migrate() {
2893
+ try {
2894
+ const v1 = localStorage.getItem('userConfig:v1')
2895
+ if (v1) {
2896
+ const old = JSON.parse(v1)
2897
+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
2898
+ localStorage.removeItem('userConfig:v1')
2899
+ }
2900
+ } catch {}
2901
+ }
2902
+ ```
2903
+
2904
+ **Store minimal fields from server responses:**
2905
+
2906
+ ```typescript
2907
+ // User object has 20+ fields, only store what UI needs
2908
+ function cachePrefs(user: FullUser) {
2909
+ try {
2910
+ localStorage.setItem('prefs:v1', JSON.stringify({
2911
+ theme: user.preferences.theme,
2912
+ notifications: user.preferences.notifications
2913
+ }))
2914
+ } catch {}
2915
+ }
2916
+ ```
2917
+
2918
+ **Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
2919
+
2920
+ **Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
2921
+ ---
2922
+ title: Avoid Barrel File Imports
2923
+ impact: CRITICAL
2924
+ impactDescription: 200-800ms import cost, slow builds
2925
+ tags: bundle, imports, tree-shaking, barrel-files, performance
2926
+ ---
2927
+
2928
+ ## Avoid Barrel File Imports
2929
+
2930
+ 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'`).
2931
+
2932
+ 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.
2933
+
2934
+ **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.
2935
+
2936
+ **Incorrect (imports entire library):**
2937
+
2938
+ ```tsx
2939
+ import { Check, X, Menu } from 'lucide-react'
2940
+ // Loads 1,583 modules, takes ~2.8s extra in dev
2941
+ // Runtime cost: 200-800ms on every cold start
2942
+
2943
+ import { Button, TextField } from '@mui/material'
2944
+ // Loads 2,225 modules, takes ~4.2s extra in dev
2945
+ ```
2946
+
2947
+ **Correct (imports only what you need):**
2948
+
2949
+ ```tsx
2950
+ import Check from 'lucide-react/dist/esm/icons/check'
2951
+ import X from 'lucide-react/dist/esm/icons/x'
2952
+ import Menu from 'lucide-react/dist/esm/icons/menu'
2953
+ // Loads only 3 modules (~2KB vs ~1MB)
2954
+
2955
+ import Button from '@mui/material/Button'
2956
+ import TextField from '@mui/material/TextField'
2957
+ // Loads only what you use
2958
+ ```
2959
+
2960
+ **Alternative (Next.js 13.5+):**
2961
+
2962
+ ```js
2963
+ // next.config.js - use optimizePackageImports
2964
+ module.exports = {
2965
+ experimental: {
2966
+ optimizePackageImports: ['lucide-react', '@mui/material']
2967
+ }
2968
+ }
2969
+
2970
+ // Then you can keep the ergonomic barrel imports:
2971
+ import { Check, X, Menu } from 'lucide-react'
2972
+ // Automatically transformed to direct imports at build time
2973
+ ```
2974
+
2975
+ Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
2976
+
2977
+ 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`.
2978
+
2979
+ Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
2980
+ ---
2981
+ title: Do not wrap a simple expression with a primitive result type in useMemo
2982
+ impact: LOW-MEDIUM
2983
+ impactDescription: wasted computation on every render
2984
+ tags: rerender, useMemo, optimization
2985
+ ---
2986
+
2987
+ ## Do not wrap a simple expression with a primitive result type in useMemo
2988
+
2989
+ When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.
2990
+ Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
2991
+
2992
+ **Incorrect:**
2993
+
2994
+ ```tsx
2995
+ function Header({ user, notifications }: Props) {
2996
+ const isLoading = useMemo(() => {
2997
+ return user.isLoading || notifications.isLoading
2998
+ }, [user.isLoading, notifications.isLoading])
2999
+
3000
+ if (isLoading) return <Skeleton />
3001
+ // return some markup
3002
+ }
3003
+ ```
3004
+
3005
+ **Correct:**
3006
+
3007
+ ```tsx
3008
+ function Header({ user, notifications }: Props) {
3009
+ const isLoading = user.isLoading || notifications.isLoading
3010
+
3011
+ if (isLoading) return <Skeleton />
3012
+ // return some markup
3013
+ }
3014
+ ```