@brunosps00/dev-workflow 0.0.5 → 0.0.7

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 (166) hide show
  1. package/bin/dev-workflow.js +6 -4
  2. package/lib/constants.js +11 -0
  3. package/lib/init.js +36 -12
  4. package/lib/wrappers.js +8 -2
  5. package/package.json +1 -1
  6. package/scaffold/pt-br/commands/dw-analyze-project.md +3 -3
  7. package/scaffold/pt-br/commands/dw-bugfix.md +6 -6
  8. package/scaffold/pt-br/commands/dw-code-review.md +2 -2
  9. package/scaffold/pt-br/commands/dw-create-tasks.md +4 -4
  10. package/scaffold/pt-br/commands/dw-generate-pr.md +3 -3
  11. package/scaffold/pt-br/commands/dw-help.md +50 -50
  12. package/scaffold/pt-br/commands/dw-review-implementation.md +3 -3
  13. package/scaffold/pt-br/commands/dw-run-plan.md +8 -8
  14. package/scaffold/pt-br/commands/dw-run-task.md +3 -3
  15. package/scaffold/pt-br/templates/tasks-template.md +2 -2
  16. package/scaffold/skills/agent-browser/SKILL.md +750 -0
  17. package/scaffold/skills/agent-browser/references/authentication.md +303 -0
  18. package/scaffold/skills/agent-browser/references/commands.md +295 -0
  19. package/scaffold/skills/agent-browser/references/profiling.md +120 -0
  20. package/scaffold/skills/agent-browser/references/proxy-support.md +194 -0
  21. package/scaffold/skills/agent-browser/references/session-management.md +193 -0
  22. package/scaffold/skills/agent-browser/references/snapshot-refs.md +219 -0
  23. package/scaffold/skills/agent-browser/references/video-recording.md +173 -0
  24. package/scaffold/skills/agent-browser/templates/authenticated-session.sh +105 -0
  25. package/scaffold/skills/agent-browser/templates/capture-workflow.sh +69 -0
  26. package/scaffold/skills/agent-browser/templates/form-automation.sh +62 -0
  27. package/scaffold/skills/humanizer/README.md +143 -0
  28. package/scaffold/skills/humanizer/SKILL.md +488 -0
  29. package/scaffold/skills/humanizer/WARP.md +53 -0
  30. package/scaffold/skills/remotion-best-practices/SKILL.md +61 -0
  31. package/scaffold/skills/remotion-best-practices/rules/3d.md +86 -0
  32. package/scaffold/skills/remotion-best-practices/rules/animations.md +27 -0
  33. package/scaffold/skills/remotion-best-practices/rules/assets/charts-bar-chart.tsx +173 -0
  34. package/scaffold/skills/remotion-best-practices/rules/assets/text-animations-typewriter.tsx +100 -0
  35. package/scaffold/skills/remotion-best-practices/rules/assets/text-animations-word-highlight.tsx +103 -0
  36. package/scaffold/skills/remotion-best-practices/rules/assets.md +78 -0
  37. package/scaffold/skills/remotion-best-practices/rules/audio-visualization.md +198 -0
  38. package/scaffold/skills/remotion-best-practices/rules/audio.md +169 -0
  39. package/scaffold/skills/remotion-best-practices/rules/calculate-metadata.md +134 -0
  40. package/scaffold/skills/remotion-best-practices/rules/can-decode.md +75 -0
  41. package/scaffold/skills/remotion-best-practices/rules/charts.md +120 -0
  42. package/scaffold/skills/remotion-best-practices/rules/compositions.md +154 -0
  43. package/scaffold/skills/remotion-best-practices/rules/display-captions.md +184 -0
  44. package/scaffold/skills/remotion-best-practices/rules/extract-frames.md +229 -0
  45. package/scaffold/skills/remotion-best-practices/rules/ffmpeg.md +38 -0
  46. package/scaffold/skills/remotion-best-practices/rules/fonts.md +152 -0
  47. package/scaffold/skills/remotion-best-practices/rules/get-audio-duration.md +58 -0
  48. package/scaffold/skills/remotion-best-practices/rules/get-video-dimensions.md +68 -0
  49. package/scaffold/skills/remotion-best-practices/rules/get-video-duration.md +60 -0
  50. package/scaffold/skills/remotion-best-practices/rules/gifs.md +141 -0
  51. package/scaffold/skills/remotion-best-practices/rules/images.md +134 -0
  52. package/scaffold/skills/remotion-best-practices/rules/import-srt-captions.md +69 -0
  53. package/scaffold/skills/remotion-best-practices/rules/light-leaks.md +73 -0
  54. package/scaffold/skills/remotion-best-practices/rules/lottie.md +70 -0
  55. package/scaffold/skills/remotion-best-practices/rules/maps.md +412 -0
  56. package/scaffold/skills/remotion-best-practices/rules/measuring-dom-nodes.md +34 -0
  57. package/scaffold/skills/remotion-best-practices/rules/measuring-text.md +140 -0
  58. package/scaffold/skills/remotion-best-practices/rules/parameters.md +109 -0
  59. package/scaffold/skills/remotion-best-practices/rules/sequencing.md +118 -0
  60. package/scaffold/skills/remotion-best-practices/rules/sfx.md +26 -0
  61. package/scaffold/skills/remotion-best-practices/rules/subtitles.md +36 -0
  62. package/scaffold/skills/remotion-best-practices/rules/tailwind.md +11 -0
  63. package/scaffold/skills/remotion-best-practices/rules/text-animations.md +20 -0
  64. package/scaffold/skills/remotion-best-practices/rules/timing.md +179 -0
  65. package/scaffold/skills/remotion-best-practices/rules/transcribe-captions.md +70 -0
  66. package/scaffold/skills/remotion-best-practices/rules/transitions.md +197 -0
  67. package/scaffold/skills/remotion-best-practices/rules/transparent-videos.md +106 -0
  68. package/scaffold/skills/remotion-best-practices/rules/trimming.md +51 -0
  69. package/scaffold/skills/remotion-best-practices/rules/videos.md +171 -0
  70. package/scaffold/skills/remotion-best-practices/rules/voiceover.md +99 -0
  71. package/scaffold/skills/security-review/LICENSE +22 -0
  72. package/scaffold/skills/security-review/SKILL.md +312 -0
  73. package/scaffold/skills/security-review/infrastructure/docker.md +432 -0
  74. package/scaffold/skills/security-review/languages/javascript.md +388 -0
  75. package/scaffold/skills/security-review/languages/python.md +363 -0
  76. package/scaffold/skills/security-review/references/api-security.md +519 -0
  77. package/scaffold/skills/security-review/references/authentication.md +353 -0
  78. package/scaffold/skills/security-review/references/authorization.md +372 -0
  79. package/scaffold/skills/security-review/references/business-logic.md +443 -0
  80. package/scaffold/skills/security-review/references/cryptography.md +329 -0
  81. package/scaffold/skills/security-review/references/csrf.md +398 -0
  82. package/scaffold/skills/security-review/references/data-protection.md +378 -0
  83. package/scaffold/skills/security-review/references/deserialization.md +410 -0
  84. package/scaffold/skills/security-review/references/error-handling.md +436 -0
  85. package/scaffold/skills/security-review/references/file-security.md +457 -0
  86. package/scaffold/skills/security-review/references/injection.md +259 -0
  87. package/scaffold/skills/security-review/references/logging.md +433 -0
  88. package/scaffold/skills/security-review/references/misconfiguration.md +435 -0
  89. package/scaffold/skills/security-review/references/modern-threats.md +475 -0
  90. package/scaffold/skills/security-review/references/ssrf.md +415 -0
  91. package/scaffold/skills/security-review/references/supply-chain.md +405 -0
  92. package/scaffold/skills/security-review/references/xss.md +336 -0
  93. package/scaffold/skills/vercel-react-best-practices/AGENTS.md +3648 -0
  94. package/scaffold/skills/vercel-react-best-practices/README.md +123 -0
  95. package/scaffold/skills/vercel-react-best-practices/SKILL.md +146 -0
  96. package/scaffold/skills/vercel-react-best-practices/rules/_sections.md +46 -0
  97. package/scaffold/skills/vercel-react-best-practices/rules/_template.md +28 -0
  98. package/scaffold/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +55 -0
  99. package/scaffold/skills/vercel-react-best-practices/rules/advanced-init-once.md +42 -0
  100. package/scaffold/skills/vercel-react-best-practices/rules/advanced-use-latest.md +39 -0
  101. package/scaffold/skills/vercel-react-best-practices/rules/async-api-routes.md +38 -0
  102. package/scaffold/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md +37 -0
  103. package/scaffold/skills/vercel-react-best-practices/rules/async-defer-await.md +82 -0
  104. package/scaffold/skills/vercel-react-best-practices/rules/async-dependencies.md +51 -0
  105. package/scaffold/skills/vercel-react-best-practices/rules/async-parallel.md +28 -0
  106. package/scaffold/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +99 -0
  107. package/scaffold/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +60 -0
  108. package/scaffold/skills/vercel-react-best-practices/rules/bundle-conditional.md +31 -0
  109. package/scaffold/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +49 -0
  110. package/scaffold/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +35 -0
  111. package/scaffold/skills/vercel-react-best-practices/rules/bundle-preload.md +50 -0
  112. package/scaffold/skills/vercel-react-best-practices/rules/client-event-listeners.md +74 -0
  113. package/scaffold/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +71 -0
  114. package/scaffold/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +48 -0
  115. package/scaffold/skills/vercel-react-best-practices/rules/client-swr-dedup.md +56 -0
  116. package/scaffold/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +107 -0
  117. package/scaffold/skills/vercel-react-best-practices/rules/js-cache-function-results.md +80 -0
  118. package/scaffold/skills/vercel-react-best-practices/rules/js-cache-property-access.md +28 -0
  119. package/scaffold/skills/vercel-react-best-practices/rules/js-cache-storage.md +70 -0
  120. package/scaffold/skills/vercel-react-best-practices/rules/js-combine-iterations.md +32 -0
  121. package/scaffold/skills/vercel-react-best-practices/rules/js-early-exit.md +50 -0
  122. package/scaffold/skills/vercel-react-best-practices/rules/js-flatmap-filter.md +60 -0
  123. package/scaffold/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +45 -0
  124. package/scaffold/skills/vercel-react-best-practices/rules/js-index-maps.md +37 -0
  125. package/scaffold/skills/vercel-react-best-practices/rules/js-length-check-first.md +49 -0
  126. package/scaffold/skills/vercel-react-best-practices/rules/js-min-max-loop.md +82 -0
  127. package/scaffold/skills/vercel-react-best-practices/rules/js-request-idle-callback.md +105 -0
  128. package/scaffold/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +24 -0
  129. package/scaffold/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +57 -0
  130. package/scaffold/skills/vercel-react-best-practices/rules/rendering-activity.md +26 -0
  131. package/scaffold/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
  132. package/scaffold/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +40 -0
  133. package/scaffold/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +38 -0
  134. package/scaffold/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
  135. package/scaffold/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
  136. package/scaffold/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +30 -0
  137. package/scaffold/skills/vercel-react-best-practices/rules/rendering-resource-hints.md +85 -0
  138. package/scaffold/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md +68 -0
  139. package/scaffold/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +28 -0
  140. package/scaffold/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md +75 -0
  141. package/scaffold/skills/vercel-react-best-practices/rules/rerender-defer-reads.md +39 -0
  142. package/scaffold/skills/vercel-react-best-practices/rules/rerender-dependencies.md +45 -0
  143. package/scaffold/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md +40 -0
  144. package/scaffold/skills/vercel-react-best-practices/rules/rerender-derived-state.md +29 -0
  145. package/scaffold/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md +74 -0
  146. package/scaffold/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
  147. package/scaffold/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md +38 -0
  148. package/scaffold/skills/vercel-react-best-practices/rules/rerender-memo.md +44 -0
  149. package/scaffold/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md +45 -0
  150. package/scaffold/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md +82 -0
  151. package/scaffold/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md +35 -0
  152. package/scaffold/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md +64 -0
  153. package/scaffold/skills/vercel-react-best-practices/rules/rerender-transitions.md +40 -0
  154. package/scaffold/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md +59 -0
  155. package/scaffold/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md +73 -0
  156. package/scaffold/skills/vercel-react-best-practices/rules/server-after-nonblocking.md +73 -0
  157. package/scaffold/skills/vercel-react-best-practices/rules/server-auth-actions.md +96 -0
  158. package/scaffold/skills/vercel-react-best-practices/rules/server-cache-lru.md +41 -0
  159. package/scaffold/skills/vercel-react-best-practices/rules/server-cache-react.md +76 -0
  160. package/scaffold/skills/vercel-react-best-practices/rules/server-dedup-props.md +65 -0
  161. package/scaffold/skills/vercel-react-best-practices/rules/server-hoist-static-io.md +149 -0
  162. package/scaffold/skills/vercel-react-best-practices/rules/server-parallel-fetching.md +83 -0
  163. package/scaffold/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md +34 -0
  164. package/scaffold/skills/vercel-react-best-practices/rules/server-serialization.md +38 -0
  165. package/scaffold/skills/webapp-testing/SKILL.md +133 -0
  166. package/scaffold/skills/webapp-testing/assets/test-helper.js +56 -0
@@ -0,0 +1,3648 @@
1
+ # React Best Practices
2
+
3
+ **Version 1.0.0**
4
+ Vercel Engineering
5
+ January 2026
6
+
7
+ > **Note:**
8
+ > This document is mainly for agents and LLMs to follow when maintaining,
9
+ > generating, or refactoring React and Next.js codebases. Humans
10
+ > may also find it useful, but guidance here is optimized for automation
11
+ > and consistency by AI-assisted workflows.
12
+
13
+ ---
14
+
15
+ ## Abstract
16
+
17
+ Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.
18
+
19
+ ---
20
+
21
+ ## Table of Contents
22
+
23
+ 1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**
24
+ - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags)
25
+ - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed)
26
+ - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization)
27
+ - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes)
28
+ - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations)
29
+ - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries)
30
+ 2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**
31
+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)
32
+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)
33
+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)
34
+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)
35
+ - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent)
36
+ 3. [Server-Side Performance](#3-server-side-performance) — **HIGH**
37
+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)
38
+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)
39
+ - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching)
40
+ - 3.4 [Hoist Static I/O to Module Level](#34-hoist-static-io-to-module-level)
41
+ - 3.5 [Minimize Serialization at RSC Boundaries](#35-minimize-serialization-at-rsc-boundaries)
42
+ - 3.6 [Parallel Data Fetching with Component Composition](#36-parallel-data-fetching-with-component-composition)
43
+ - 3.7 [Parallel Nested Data Fetching](#37-parallel-nested-data-fetching)
44
+ - 3.8 [Per-Request Deduplication with React.cache()](#38-per-request-deduplication-with-reactcache)
45
+ - 3.9 [Use after() for Non-Blocking Operations](#39-use-after-for-non-blocking-operations)
46
+ 4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**
47
+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)
48
+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)
49
+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)
50
+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)
51
+ 5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**
52
+ - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)
53
+ - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)
54
+ - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)
55
+ - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components)
56
+ - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)
57
+ - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components)
58
+ - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies)
59
+ - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers)
60
+ - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations)
61
+ - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state)
62
+ - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates)
63
+ - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization)
64
+ - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates)
65
+ - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders)
66
+ - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values)
67
+ 6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**
68
+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)
69
+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)
70
+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)
71
+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)
72
+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)
73
+ - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)
74
+ - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)
75
+ - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags)
76
+ - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering)
77
+ - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints)
78
+ - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states)
79
+ 7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**
80
+ - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)
81
+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)
82
+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)
83
+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)
84
+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)
85
+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)
86
+ - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback)
87
+ - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons)
88
+ - 7.9 [Early Return from Functions](#79-early-return-from-functions)
89
+ - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation)
90
+ - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass)
91
+ - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort)
92
+ - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups)
93
+ - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability)
94
+ 8. [Advanced Patterns](#8-advanced-patterns) — **LOW**
95
+ - 8.1 [Initialize App Once, Not Per Mount](#81-initialize-app-once-not-per-mount)
96
+ - 8.2 [Store Event Handlers in Refs](#82-store-event-handlers-in-refs)
97
+ - 8.3 [useEffectEvent for Stable Callback Refs](#83-useeffectevent-for-stable-callback-refs)
98
+
99
+ ---
100
+
101
+ ## 1. Eliminating Waterfalls
102
+
103
+ **Impact: CRITICAL**
104
+
105
+ Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
106
+
107
+ ### 1.1 Check Cheap Conditions Before Async Flags
108
+
109
+ **Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)**
110
+
111
+ When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
112
+
113
+ This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
114
+
115
+ **Incorrect:**
116
+
117
+ ```typescript
118
+ const someFlag = await getFlag()
119
+
120
+ if (someFlag && someCondition) {
121
+ // ...
122
+ }
123
+ ```
124
+
125
+ **Correct:**
126
+
127
+ ```typescript
128
+ if (someCondition) {
129
+ const someFlag = await getFlag()
130
+ if (someFlag) {
131
+ // ...
132
+ }
133
+ }
134
+ ```
135
+
136
+ This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
137
+
138
+ Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
139
+
140
+ ### 1.2 Defer Await Until Needed
141
+
142
+ **Impact: HIGH (avoids blocking unused code paths)**
143
+
144
+ Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
145
+
146
+ **Incorrect: blocks both branches**
147
+
148
+ ```typescript
149
+ async function handleRequest(userId: string, skipProcessing: boolean) {
150
+ const userData = await fetchUserData(userId)
151
+
152
+ if (skipProcessing) {
153
+ // Returns immediately but still waited for userData
154
+ return { skipped: true }
155
+ }
156
+
157
+ // Only this branch uses userData
158
+ return processUserData(userData)
159
+ }
160
+ ```
161
+
162
+ **Correct: only blocks when needed**
163
+
164
+ ```typescript
165
+ async function handleRequest(userId: string, skipProcessing: boolean) {
166
+ if (skipProcessing) {
167
+ // Returns immediately without waiting
168
+ return { skipped: true }
169
+ }
170
+
171
+ // Fetch only when needed
172
+ const userData = await fetchUserData(userId)
173
+ return processUserData(userData)
174
+ }
175
+ ```
176
+
177
+ **Another example: early return optimization**
178
+
179
+ ```typescript
180
+ // Incorrect: always fetches permissions
181
+ async function updateResource(resourceId: string, userId: string) {
182
+ const permissions = await fetchPermissions(userId)
183
+ const resource = await getResource(resourceId)
184
+
185
+ if (!resource) {
186
+ return { error: 'Not found' }
187
+ }
188
+
189
+ if (!permissions.canEdit) {
190
+ return { error: 'Forbidden' }
191
+ }
192
+
193
+ return await updateResourceData(resource, permissions)
194
+ }
195
+
196
+ // Correct: fetches only when needed
197
+ async function updateResource(resourceId: string, userId: string) {
198
+ const resource = await getResource(resourceId)
199
+
200
+ if (!resource) {
201
+ return { error: 'Not found' }
202
+ }
203
+
204
+ const permissions = await fetchPermissions(userId)
205
+
206
+ if (!permissions.canEdit) {
207
+ return { error: 'Forbidden' }
208
+ }
209
+
210
+ return await updateResourceData(resource, permissions)
211
+ }
212
+ ```
213
+
214
+ This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
215
+
216
+ For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
217
+
218
+ ### 1.3 Dependency-Based Parallelization
219
+
220
+ **Impact: CRITICAL (2-10× improvement)**
221
+
222
+ For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
223
+
224
+ **Incorrect: profile waits for config unnecessarily**
225
+
226
+ ```typescript
227
+ const [user, config] = await Promise.all([
228
+ fetchUser(),
229
+ fetchConfig()
230
+ ])
231
+ const profile = await fetchProfile(user.id)
232
+ ```
233
+
234
+ **Correct: config and profile run in parallel**
235
+
236
+ ```typescript
237
+ import { all } from 'better-all'
238
+
239
+ const { user, config, profile } = await all({
240
+ async user() { return fetchUser() },
241
+ async config() { return fetchConfig() },
242
+ async profile() {
243
+ return fetchProfile((await this.$.user).id)
244
+ }
245
+ })
246
+ ```
247
+
248
+ **Alternative without extra dependencies:**
249
+
250
+ ```typescript
251
+ const userPromise = fetchUser()
252
+ const profilePromise = userPromise.then(user => fetchProfile(user.id))
253
+
254
+ const [user, config, profile] = await Promise.all([
255
+ userPromise,
256
+ fetchConfig(),
257
+ profilePromise
258
+ ])
259
+ ```
260
+
261
+ We can also create all the promises first, and do `Promise.all()` at the end.
262
+
263
+ Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
264
+
265
+ ### 1.4 Prevent Waterfall Chains in API Routes
266
+
267
+ **Impact: CRITICAL (2-10× improvement)**
268
+
269
+ In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
270
+
271
+ **Incorrect: config waits for auth, data waits for both**
272
+
273
+ ```typescript
274
+ export async function GET(request: Request) {
275
+ const session = await auth()
276
+ const config = await fetchConfig()
277
+ const data = await fetchData(session.user.id)
278
+ return Response.json({ data, config })
279
+ }
280
+ ```
281
+
282
+ **Correct: auth and config start immediately**
283
+
284
+ ```typescript
285
+ export async function GET(request: Request) {
286
+ const sessionPromise = auth()
287
+ const configPromise = fetchConfig()
288
+ const session = await sessionPromise
289
+ const [config, data] = await Promise.all([
290
+ configPromise,
291
+ fetchData(session.user.id)
292
+ ])
293
+ return Response.json({ data, config })
294
+ }
295
+ ```
296
+
297
+ For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
298
+
299
+ ### 1.5 Promise.all() for Independent Operations
300
+
301
+ **Impact: CRITICAL (2-10× improvement)**
302
+
303
+ When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
304
+
305
+ **Incorrect: sequential execution, 3 round trips**
306
+
307
+ ```typescript
308
+ const user = await fetchUser()
309
+ const posts = await fetchPosts()
310
+ const comments = await fetchComments()
311
+ ```
312
+
313
+ **Correct: parallel execution, 1 round trip**
314
+
315
+ ```typescript
316
+ const [user, posts, comments] = await Promise.all([
317
+ fetchUser(),
318
+ fetchPosts(),
319
+ fetchComments()
320
+ ])
321
+ ```
322
+
323
+ ### 1.6 Strategic Suspense Boundaries
324
+
325
+ **Impact: HIGH (faster initial paint)**
326
+
327
+ Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
328
+
329
+ **Incorrect: wrapper blocked by data fetching**
330
+
331
+ ```tsx
332
+ async function Page() {
333
+ const data = await fetchData() // Blocks entire page
334
+
335
+ return (
336
+ <div>
337
+ <div>Sidebar</div>
338
+ <div>Header</div>
339
+ <div>
340
+ <DataDisplay data={data} />
341
+ </div>
342
+ <div>Footer</div>
343
+ </div>
344
+ )
345
+ }
346
+ ```
347
+
348
+ The entire layout waits for data even though only the middle section needs it.
349
+
350
+ **Correct: wrapper shows immediately, data streams in**
351
+
352
+ ```tsx
353
+ function Page() {
354
+ return (
355
+ <div>
356
+ <div>Sidebar</div>
357
+ <div>Header</div>
358
+ <div>
359
+ <Suspense fallback={<Skeleton />}>
360
+ <DataDisplay />
361
+ </Suspense>
362
+ </div>
363
+ <div>Footer</div>
364
+ </div>
365
+ )
366
+ }
367
+
368
+ async function DataDisplay() {
369
+ const data = await fetchData() // Only blocks this component
370
+ return <div>{data.content}</div>
371
+ }
372
+ ```
373
+
374
+ Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
375
+
376
+ **Alternative: share promise across components**
377
+
378
+ ```tsx
379
+ function Page() {
380
+ // Start fetch immediately, but don't await
381
+ const dataPromise = fetchData()
382
+
383
+ return (
384
+ <div>
385
+ <div>Sidebar</div>
386
+ <div>Header</div>
387
+ <Suspense fallback={<Skeleton />}>
388
+ <DataDisplay dataPromise={dataPromise} />
389
+ <DataSummary dataPromise={dataPromise} />
390
+ </Suspense>
391
+ <div>Footer</div>
392
+ </div>
393
+ )
394
+ }
395
+
396
+ function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
397
+ const data = use(dataPromise) // Unwraps the promise
398
+ return <div>{data.content}</div>
399
+ }
400
+
401
+ function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
402
+ const data = use(dataPromise) // Reuses the same promise
403
+ return <div>{data.summary}</div>
404
+ }
405
+ ```
406
+
407
+ Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
408
+
409
+ **When NOT to use this pattern:**
410
+
411
+ - Critical data needed for layout decisions (affects positioning)
412
+
413
+ - SEO-critical content above the fold
414
+
415
+ - Small, fast queries where suspense overhead isn't worth it
416
+
417
+ - When you want to avoid layout shift (loading → content jump)
418
+
419
+ **Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
420
+
421
+ ---
422
+
423
+ ## 2. Bundle Size Optimization
424
+
425
+ **Impact: CRITICAL**
426
+
427
+ Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
428
+
429
+ ### 2.1 Avoid Barrel File Imports
430
+
431
+ **Impact: CRITICAL (200-800ms import cost, slow builds)**
432
+
433
+ 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'`).
434
+
435
+ 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.
436
+
437
+ **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.
438
+
439
+ **Incorrect: imports entire library**
440
+
441
+ ```tsx
442
+ import { Check, X, Menu } from 'lucide-react'
443
+ // Loads 1,583 modules, takes ~2.8s extra in dev
444
+ // Runtime cost: 200-800ms on every cold start
445
+
446
+ import { Button, TextField } from '@mui/material'
447
+ // Loads 2,225 modules, takes ~4.2s extra in dev
448
+ ```
449
+
450
+ **Correct - Next.js 13.5+ (recommended):**
451
+
452
+ ```tsx
453
+ // Keep the standard imports - Next.js transforms them to direct imports
454
+ import { Check, X, Menu } from 'lucide-react'
455
+ // Full TypeScript support, no manual path wrangling
456
+ ```
457
+
458
+ This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
459
+
460
+ **Correct - Direct imports (non-Next.js projects):**
461
+
462
+ ```tsx
463
+ import Button from '@mui/material/Button'
464
+ import TextField from '@mui/material/TextField'
465
+ // Loads only what you use
466
+ ```
467
+
468
+ > **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
469
+
470
+ These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
471
+
472
+ 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`.
473
+
474
+ Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
475
+
476
+ ### 2.2 Conditional Module Loading
477
+
478
+ **Impact: HIGH (loads large data only when needed)**
479
+
480
+ Load large data or modules only when a feature is activated.
481
+
482
+ **Example: lazy-load animation frames**
483
+
484
+ ```tsx
485
+ function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {
486
+ const [frames, setFrames] = useState<Frame[] | null>(null)
487
+
488
+ useEffect(() => {
489
+ if (enabled && !frames && typeof window !== 'undefined') {
490
+ import('./animation-frames.js')
491
+ .then(mod => setFrames(mod.frames))
492
+ .catch(() => setEnabled(false))
493
+ }
494
+ }, [enabled, frames, setEnabled])
495
+
496
+ if (!frames) return <Skeleton />
497
+ return <Canvas frames={frames} />
498
+ }
499
+ ```
500
+
501
+ The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
502
+
503
+ ### 2.3 Defer Non-Critical Third-Party Libraries
504
+
505
+ **Impact: MEDIUM (loads after hydration)**
506
+
507
+ Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
508
+
509
+ **Incorrect: blocks initial bundle**
510
+
511
+ ```tsx
512
+ import { Analytics } from '@vercel/analytics/react'
513
+
514
+ export default function RootLayout({ children }) {
515
+ return (
516
+ <html>
517
+ <body>
518
+ {children}
519
+ <Analytics />
520
+ </body>
521
+ </html>
522
+ )
523
+ }
524
+ ```
525
+
526
+ **Correct: loads after hydration**
527
+
528
+ ```tsx
529
+ import dynamic from 'next/dynamic'
530
+
531
+ const Analytics = dynamic(
532
+ () => import('@vercel/analytics/react').then(m => m.Analytics),
533
+ { ssr: false }
534
+ )
535
+
536
+ export default function RootLayout({ children }) {
537
+ return (
538
+ <html>
539
+ <body>
540
+ {children}
541
+ <Analytics />
542
+ </body>
543
+ </html>
544
+ )
545
+ }
546
+ ```
547
+
548
+ ### 2.4 Dynamic Imports for Heavy Components
549
+
550
+ **Impact: CRITICAL (directly affects TTI and LCP)**
551
+
552
+ Use `next/dynamic` to lazy-load large components not needed on initial render.
553
+
554
+ **Incorrect: Monaco bundles with main chunk ~300KB**
555
+
556
+ ```tsx
557
+ import { MonacoEditor } from './monaco-editor'
558
+
559
+ function CodePanel({ code }: { code: string }) {
560
+ return <MonacoEditor value={code} />
561
+ }
562
+ ```
563
+
564
+ **Correct: Monaco loads on demand**
565
+
566
+ ```tsx
567
+ import dynamic from 'next/dynamic'
568
+
569
+ const MonacoEditor = dynamic(
570
+ () => import('./monaco-editor').then(m => m.MonacoEditor),
571
+ { ssr: false }
572
+ )
573
+
574
+ function CodePanel({ code }: { code: string }) {
575
+ return <MonacoEditor value={code} />
576
+ }
577
+ ```
578
+
579
+ ### 2.5 Preload Based on User Intent
580
+
581
+ **Impact: MEDIUM (reduces perceived latency)**
582
+
583
+ Preload heavy bundles before they're needed to reduce perceived latency.
584
+
585
+ **Example: preload on hover/focus**
586
+
587
+ ```tsx
588
+ function EditorButton({ onClick }: { onClick: () => void }) {
589
+ const preload = () => {
590
+ if (typeof window !== 'undefined') {
591
+ void import('./monaco-editor')
592
+ }
593
+ }
594
+
595
+ return (
596
+ <button
597
+ onMouseEnter={preload}
598
+ onFocus={preload}
599
+ onClick={onClick}
600
+ >
601
+ Open Editor
602
+ </button>
603
+ )
604
+ }
605
+ ```
606
+
607
+ **Example: preload when feature flag is enabled**
608
+
609
+ ```tsx
610
+ function FlagsProvider({ children, flags }: Props) {
611
+ useEffect(() => {
612
+ if (flags.editorEnabled && typeof window !== 'undefined') {
613
+ void import('./monaco-editor').then(mod => mod.init())
614
+ }
615
+ }, [flags.editorEnabled])
616
+
617
+ return <FlagsContext.Provider value={flags}>
618
+ {children}
619
+ </FlagsContext.Provider>
620
+ }
621
+ ```
622
+
623
+ The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
624
+
625
+ ---
626
+
627
+ ## 3. Server-Side Performance
628
+
629
+ **Impact: HIGH**
630
+
631
+ Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
632
+
633
+ ### 3.1 Authenticate Server Actions Like API Routes
634
+
635
+ **Impact: CRITICAL (prevents unauthorized access to server mutations)**
636
+
637
+ 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.
638
+
639
+ 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."
640
+
641
+ **Incorrect: no authentication check**
642
+
643
+ ```typescript
644
+ 'use server'
645
+
646
+ export async function deleteUser(userId: string) {
647
+ // Anyone can call this! No auth check
648
+ await db.user.delete({ where: { id: userId } })
649
+ return { success: true }
650
+ }
651
+ ```
652
+
653
+ **Correct: authentication inside the action**
654
+
655
+ ```typescript
656
+ 'use server'
657
+
658
+ import { verifySession } from '@/lib/auth'
659
+ import { unauthorized } from '@/lib/errors'
660
+
661
+ export async function deleteUser(userId: string) {
662
+ // Always check auth inside the action
663
+ const session = await verifySession()
664
+
665
+ if (!session) {
666
+ throw unauthorized('Must be logged in')
667
+ }
668
+
669
+ // Check authorization too
670
+ if (session.user.role !== 'admin' && session.user.id !== userId) {
671
+ throw unauthorized('Cannot delete other users')
672
+ }
673
+
674
+ await db.user.delete({ where: { id: userId } })
675
+ return { success: true }
676
+ }
677
+ ```
678
+
679
+ **With input validation:**
680
+
681
+ ```typescript
682
+ 'use server'
683
+
684
+ import { verifySession } from '@/lib/auth'
685
+ import { z } from 'zod'
686
+
687
+ const updateProfileSchema = z.object({
688
+ userId: z.string().uuid(),
689
+ name: z.string().min(1).max(100),
690
+ email: z.string().email()
691
+ })
692
+
693
+ export async function updateProfile(data: unknown) {
694
+ // Validate input first
695
+ const validated = updateProfileSchema.parse(data)
696
+
697
+ // Then authenticate
698
+ const session = await verifySession()
699
+ if (!session) {
700
+ throw new Error('Unauthorized')
701
+ }
702
+
703
+ // Then authorize
704
+ if (session.user.id !== validated.userId) {
705
+ throw new Error('Can only update own profile')
706
+ }
707
+
708
+ // Finally perform the mutation
709
+ await db.user.update({
710
+ where: { id: validated.userId },
711
+ data: {
712
+ name: validated.name,
713
+ email: validated.email
714
+ }
715
+ })
716
+
717
+ return { success: true }
718
+ }
719
+ ```
720
+
721
+ Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)
722
+
723
+ ### 3.2 Avoid Duplicate Serialization in RSC Props
724
+
725
+ **Impact: LOW (reduces network payload by avoiding duplicate serialization)**
726
+
727
+ 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.
728
+
729
+ **Incorrect: duplicates array**
730
+
731
+ ```tsx
732
+ // RSC: sends 6 strings (2 arrays × 3 items)
733
+ <ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />
734
+ ```
735
+
736
+ **Correct: sends 3 strings**
737
+
738
+ ```tsx
739
+ // RSC: send once
740
+ <ClientList usernames={usernames} />
741
+
742
+ // Client: transform there
743
+ 'use client'
744
+ const sorted = useMemo(() => [...usernames].sort(), [usernames])
745
+ ```
746
+
747
+ **Nested deduplication behavior:**
748
+
749
+ ```tsx
750
+ // string[] - duplicates everything
751
+ usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings
752
+
753
+ // object[] - duplicates array structure only
754
+ users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)
755
+ ```
756
+
757
+ Deduplication works recursively. Impact varies by data type:
758
+
759
+ - `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated
760
+
761
+ - `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference
762
+
763
+ **Operations breaking deduplication: create new references**
764
+
765
+ - Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`
766
+
767
+ - Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`
768
+
769
+ **More examples:**
770
+
771
+ ```tsx
772
+ // ❌ Bad
773
+ <C users={users} active={users.filter(u => u.active)} />
774
+ <C product={product} productName={product.name} />
775
+
776
+ // ✅ Good
777
+ <C users={users} />
778
+ <C product={product} />
779
+ // Do filtering/destructuring in client
780
+ ```
781
+
782
+ **Exception:** Pass derived data when transformation is expensive or client doesn't need original.
783
+
784
+ ### 3.3 Cross-Request LRU Caching
785
+
786
+ **Impact: HIGH (caches across requests)**
787
+
788
+ `React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
789
+
790
+ **Implementation:**
791
+
792
+ ```typescript
793
+ import { LRUCache } from 'lru-cache'
794
+
795
+ const cache = new LRUCache<string, any>({
796
+ max: 1000,
797
+ ttl: 5 * 60 * 1000 // 5 minutes
798
+ })
799
+
800
+ export async function getUser(id: string) {
801
+ const cached = cache.get(id)
802
+ if (cached) return cached
803
+
804
+ const user = await db.user.findUnique({ where: { id } })
805
+ cache.set(id, user)
806
+ return user
807
+ }
808
+
809
+ // Request 1: DB query, result cached
810
+ // Request 2: cache hit, no DB query
811
+ ```
812
+
813
+ Use when sequential user actions hit multiple endpoints needing the same data within seconds.
814
+
815
+ **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.
816
+
817
+ **In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.
818
+
819
+ Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
820
+
821
+ ### 3.4 Hoist Static I/O to Module Level
822
+
823
+ **Impact: HIGH (avoids repeated file/network I/O per request)**
824
+
825
+ When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
826
+
827
+ **Incorrect: reads font file on every request**
828
+
829
+ ```typescript
830
+ // app/api/og/route.tsx
831
+ import { ImageResponse } from 'next/og'
832
+
833
+ export async function GET(request: Request) {
834
+ // Runs on EVERY request - expensive!
835
+ const fontData = await fetch(
836
+ new URL('./fonts/Inter.ttf', import.meta.url)
837
+ ).then(res => res.arrayBuffer())
838
+
839
+ const logoData = await fetch(
840
+ new URL('./images/logo.png', import.meta.url)
841
+ ).then(res => res.arrayBuffer())
842
+
843
+ return new ImageResponse(
844
+ <div style={{ fontFamily: 'Inter' }}>
845
+ <img src={logoData} />
846
+ Hello World
847
+ </div>,
848
+ { fonts: [{ name: 'Inter', data: fontData }] }
849
+ )
850
+ }
851
+ ```
852
+
853
+ **Correct: loads once at module initialization**
854
+
855
+ ```typescript
856
+ // app/api/og/route.tsx
857
+ import { ImageResponse } from 'next/og'
858
+
859
+ // Module-level: runs ONCE when module is first imported
860
+ const fontData = fetch(
861
+ new URL('./fonts/Inter.ttf', import.meta.url)
862
+ ).then(res => res.arrayBuffer())
863
+
864
+ const logoData = fetch(
865
+ new URL('./images/logo.png', import.meta.url)
866
+ ).then(res => res.arrayBuffer())
867
+
868
+ export async function GET(request: Request) {
869
+ // Await the already-started promises
870
+ const [font, logo] = await Promise.all([fontData, logoData])
871
+
872
+ return new ImageResponse(
873
+ <div style={{ fontFamily: 'Inter' }}>
874
+ <img src={logo} />
875
+ Hello World
876
+ </div>,
877
+ { fonts: [{ name: 'Inter', data: font }] }
878
+ )
879
+ }
880
+ ```
881
+
882
+ **Correct: synchronous fs at module level**
883
+
884
+ ```typescript
885
+ // app/api/og/route.tsx
886
+ import { ImageResponse } from 'next/og'
887
+ import { readFileSync } from 'fs'
888
+ import { join } from 'path'
889
+
890
+ // Synchronous read at module level - blocks only during module init
891
+ const fontData = readFileSync(
892
+ join(process.cwd(), 'public/fonts/Inter.ttf')
893
+ )
894
+
895
+ const logoData = readFileSync(
896
+ join(process.cwd(), 'public/images/logo.png')
897
+ )
898
+
899
+ export async function GET(request: Request) {
900
+ return new ImageResponse(
901
+ <div style={{ fontFamily: 'Inter' }}>
902
+ <img src={logoData} />
903
+ Hello World
904
+ </div>,
905
+ { fonts: [{ name: 'Inter', data: fontData }] }
906
+ )
907
+ }
908
+ ```
909
+
910
+ **Incorrect: reads config on every call**
911
+
912
+ ```typescript
913
+ import fs from 'node:fs/promises'
914
+
915
+ export async function processRequest(data: Data) {
916
+ const config = JSON.parse(
917
+ await fs.readFile('./config.json', 'utf-8')
918
+ )
919
+ const template = await fs.readFile('./template.html', 'utf-8')
920
+
921
+ return render(template, data, config)
922
+ }
923
+ ```
924
+
925
+ **Correct: hoists config and template to module level**
926
+
927
+ ```typescript
928
+ import fs from 'node:fs/promises'
929
+
930
+ const configPromise = fs
931
+ .readFile('./config.json', 'utf-8')
932
+ .then(JSON.parse)
933
+ const templatePromise = fs.readFile('./template.html', 'utf-8')
934
+
935
+ export async function processRequest(data: Data) {
936
+ const [config, template] = await Promise.all([
937
+ configPromise,
938
+ templatePromise,
939
+ ])
940
+
941
+ return render(template, data, config)
942
+ }
943
+ ```
944
+
945
+ When to use this pattern:
946
+
947
+ - Loading fonts for OG image generation
948
+
949
+ - Loading static logos, icons, or watermarks
950
+
951
+ - Reading configuration files that don't change at runtime
952
+
953
+ - Loading email templates or other static templates
954
+
955
+ - Any static asset that's the same across all requests
956
+
957
+ When not to use this pattern:
958
+
959
+ - Assets that vary per request or user
960
+
961
+ - Files that may change during runtime (use caching with TTL instead)
962
+
963
+ - Large files that would consume too much memory if kept loaded
964
+
965
+ - Sensitive data that shouldn't persist in memory
966
+
967
+ With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
968
+
969
+ In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
970
+
971
+ ### 3.5 Minimize Serialization at RSC Boundaries
972
+
973
+ **Impact: HIGH (reduces data transfer size)**
974
+
975
+ 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.
976
+
977
+ **Incorrect: serializes all 50 fields**
978
+
979
+ ```tsx
980
+ async function Page() {
981
+ const user = await fetchUser() // 50 fields
982
+ return <Profile user={user} />
983
+ }
984
+
985
+ 'use client'
986
+ function Profile({ user }: { user: User }) {
987
+ return <div>{user.name}</div> // uses 1 field
988
+ }
989
+ ```
990
+
991
+ **Correct: serializes only 1 field**
992
+
993
+ ```tsx
994
+ async function Page() {
995
+ const user = await fetchUser()
996
+ return <Profile name={user.name} />
997
+ }
998
+
999
+ 'use client'
1000
+ function Profile({ name }: { name: string }) {
1001
+ return <div>{name}</div>
1002
+ }
1003
+ ```
1004
+
1005
+ ### 3.6 Parallel Data Fetching with Component Composition
1006
+
1007
+ **Impact: CRITICAL (eliminates server-side waterfalls)**
1008
+
1009
+ React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
1010
+
1011
+ **Incorrect: Sidebar waits for Page's fetch to complete**
1012
+
1013
+ ```tsx
1014
+ export default async function Page() {
1015
+ const header = await fetchHeader()
1016
+ return (
1017
+ <div>
1018
+ <div>{header}</div>
1019
+ <Sidebar />
1020
+ </div>
1021
+ )
1022
+ }
1023
+
1024
+ async function Sidebar() {
1025
+ const items = await fetchSidebarItems()
1026
+ return <nav>{items.map(renderItem)}</nav>
1027
+ }
1028
+ ```
1029
+
1030
+ **Correct: both fetch simultaneously**
1031
+
1032
+ ```tsx
1033
+ async function Header() {
1034
+ const data = await fetchHeader()
1035
+ return <div>{data}</div>
1036
+ }
1037
+
1038
+ async function Sidebar() {
1039
+ const items = await fetchSidebarItems()
1040
+ return <nav>{items.map(renderItem)}</nav>
1041
+ }
1042
+
1043
+ export default function Page() {
1044
+ return (
1045
+ <div>
1046
+ <Header />
1047
+ <Sidebar />
1048
+ </div>
1049
+ )
1050
+ }
1051
+ ```
1052
+
1053
+ **Alternative with children prop:**
1054
+
1055
+ ```tsx
1056
+ async function Header() {
1057
+ const data = await fetchHeader()
1058
+ return <div>{data}</div>
1059
+ }
1060
+
1061
+ async function Sidebar() {
1062
+ const items = await fetchSidebarItems()
1063
+ return <nav>{items.map(renderItem)}</nav>
1064
+ }
1065
+
1066
+ function Layout({ children }: { children: ReactNode }) {
1067
+ return (
1068
+ <div>
1069
+ <Header />
1070
+ {children}
1071
+ </div>
1072
+ )
1073
+ }
1074
+
1075
+ export default function Page() {
1076
+ return (
1077
+ <Layout>
1078
+ <Sidebar />
1079
+ </Layout>
1080
+ )
1081
+ }
1082
+ ```
1083
+
1084
+ ### 3.7 Parallel Nested Data Fetching
1085
+
1086
+ **Impact: CRITICAL (eliminates server-side waterfalls)**
1087
+
1088
+ When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.
1089
+
1090
+ **Incorrect: a single slow item blocks all nested fetches**
1091
+
1092
+ ```tsx
1093
+ const chats = await Promise.all(
1094
+ chatIds.map(id => getChat(id))
1095
+ )
1096
+
1097
+ const chatAuthors = await Promise.all(
1098
+ chats.map(chat => getUser(chat.author))
1099
+ )
1100
+ ```
1101
+
1102
+ If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.
1103
+
1104
+ **Correct: each item chains its own nested fetch**
1105
+
1106
+ ```tsx
1107
+ const chatAuthors = await Promise.all(
1108
+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
1109
+ )
1110
+ ```
1111
+
1112
+ Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.
1113
+
1114
+ ### 3.8 Per-Request Deduplication with React.cache()
1115
+
1116
+ **Impact: MEDIUM (deduplicates within request)**
1117
+
1118
+ Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
1119
+
1120
+ **Usage:**
1121
+
1122
+ ```typescript
1123
+ import { cache } from 'react'
1124
+
1125
+ export const getCurrentUser = cache(async () => {
1126
+ const session = await auth()
1127
+ if (!session?.user?.id) return null
1128
+ return await db.user.findUnique({
1129
+ where: { id: session.user.id }
1130
+ })
1131
+ })
1132
+ ```
1133
+
1134
+ Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
1135
+
1136
+ **Avoid inline objects as arguments:**
1137
+
1138
+ `React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.
1139
+
1140
+ **Incorrect: always cache miss**
1141
+
1142
+ ```typescript
1143
+ const getUser = cache(async (params: { uid: number }) => {
1144
+ return await db.user.findUnique({ where: { id: params.uid } })
1145
+ })
1146
+
1147
+ // Each call creates new object, never hits cache
1148
+ getUser({ uid: 1 })
1149
+ getUser({ uid: 1 }) // Cache miss, runs query again
1150
+ ```
1151
+
1152
+ **Correct: cache hit**
1153
+
1154
+ ```typescript
1155
+ const params = { uid: 1 }
1156
+ getUser(params) // Query runs
1157
+ getUser(params) // Cache hit (same reference)
1158
+ ```
1159
+
1160
+ If you must pass objects, pass the same reference:
1161
+
1162
+ **Next.js-Specific Note:**
1163
+
1164
+ 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:
1165
+
1166
+ - Database queries (Prisma, Drizzle, etc.)
1167
+
1168
+ - Heavy computations
1169
+
1170
+ - Authentication checks
1171
+
1172
+ - File system operations
1173
+
1174
+ - Any non-fetch async work
1175
+
1176
+ Use `React.cache()` to deduplicate these operations across your component tree.
1177
+
1178
+ Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)
1179
+
1180
+ ### 3.9 Use after() for Non-Blocking Operations
1181
+
1182
+ **Impact: MEDIUM (faster response times)**
1183
+
1184
+ 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.
1185
+
1186
+ **Incorrect: blocks response**
1187
+
1188
+ ```tsx
1189
+ import { logUserAction } from '@/app/utils'
1190
+
1191
+ export async function POST(request: Request) {
1192
+ // Perform mutation
1193
+ await updateDatabase(request)
1194
+
1195
+ // Logging blocks the response
1196
+ const userAgent = request.headers.get('user-agent') || 'unknown'
1197
+ await logUserAction({ userAgent })
1198
+
1199
+ return new Response(JSON.stringify({ status: 'success' }), {
1200
+ status: 200,
1201
+ headers: { 'Content-Type': 'application/json' }
1202
+ })
1203
+ }
1204
+ ```
1205
+
1206
+ **Correct: non-blocking**
1207
+
1208
+ ```tsx
1209
+ import { after } from 'next/server'
1210
+ import { headers, cookies } from 'next/headers'
1211
+ import { logUserAction } from '@/app/utils'
1212
+
1213
+ export async function POST(request: Request) {
1214
+ // Perform mutation
1215
+ await updateDatabase(request)
1216
+
1217
+ // Log after response is sent
1218
+ after(async () => {
1219
+ const userAgent = (await headers()).get('user-agent') || 'unknown'
1220
+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'
1221
+
1222
+ logUserAction({ sessionCookie, userAgent })
1223
+ })
1224
+
1225
+ return new Response(JSON.stringify({ status: 'success' }), {
1226
+ status: 200,
1227
+ headers: { 'Content-Type': 'application/json' }
1228
+ })
1229
+ }
1230
+ ```
1231
+
1232
+ The response is sent immediately while logging happens in the background.
1233
+
1234
+ **Common use cases:**
1235
+
1236
+ - Analytics tracking
1237
+
1238
+ - Audit logging
1239
+
1240
+ - Sending notifications
1241
+
1242
+ - Cache invalidation
1243
+
1244
+ - Cleanup tasks
1245
+
1246
+ **Important notes:**
1247
+
1248
+ - `after()` runs even if the response fails or redirects
1249
+
1250
+ - Works in Server Actions, Route Handlers, and Server Components
1251
+
1252
+ Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)
1253
+
1254
+ ---
1255
+
1256
+ ## 4. Client-Side Data Fetching
1257
+
1258
+ **Impact: MEDIUM-HIGH**
1259
+
1260
+ Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
1261
+
1262
+ ### 4.1 Deduplicate Global Event Listeners
1263
+
1264
+ **Impact: LOW (single listener for N components)**
1265
+
1266
+ Use `useSWRSubscription()` to share global event listeners across component instances.
1267
+
1268
+ **Incorrect: N instances = N listeners**
1269
+
1270
+ ```tsx
1271
+ function useKeyboardShortcut(key: string, callback: () => void) {
1272
+ useEffect(() => {
1273
+ const handler = (e: KeyboardEvent) => {
1274
+ if (e.metaKey && e.key === key) {
1275
+ callback()
1276
+ }
1277
+ }
1278
+ window.addEventListener('keydown', handler)
1279
+ return () => window.removeEventListener('keydown', handler)
1280
+ }, [key, callback])
1281
+ }
1282
+ ```
1283
+
1284
+ When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
1285
+
1286
+ **Correct: N instances = 1 listener**
1287
+
1288
+ ```tsx
1289
+ import useSWRSubscription from 'swr/subscription'
1290
+
1291
+ // Module-level Map to track callbacks per key
1292
+ const keyCallbacks = new Map<string, Set<() => void>>()
1293
+
1294
+ function useKeyboardShortcut(key: string, callback: () => void) {
1295
+ // Register this callback in the Map
1296
+ useEffect(() => {
1297
+ if (!keyCallbacks.has(key)) {
1298
+ keyCallbacks.set(key, new Set())
1299
+ }
1300
+ keyCallbacks.get(key)!.add(callback)
1301
+
1302
+ return () => {
1303
+ const set = keyCallbacks.get(key)
1304
+ if (set) {
1305
+ set.delete(callback)
1306
+ if (set.size === 0) {
1307
+ keyCallbacks.delete(key)
1308
+ }
1309
+ }
1310
+ }
1311
+ }, [key, callback])
1312
+
1313
+ useSWRSubscription('global-keydown', () => {
1314
+ const handler = (e: KeyboardEvent) => {
1315
+ if (e.metaKey && keyCallbacks.has(e.key)) {
1316
+ keyCallbacks.get(e.key)!.forEach(cb => cb())
1317
+ }
1318
+ }
1319
+ window.addEventListener('keydown', handler)
1320
+ return () => window.removeEventListener('keydown', handler)
1321
+ })
1322
+ }
1323
+
1324
+ function Profile() {
1325
+ // Multiple shortcuts will share the same listener
1326
+ useKeyboardShortcut('p', () => { /* ... */ })
1327
+ useKeyboardShortcut('k', () => { /* ... */ })
1328
+ // ...
1329
+ }
1330
+ ```
1331
+
1332
+ ### 4.2 Use Passive Event Listeners for Scrolling Performance
1333
+
1334
+ **Impact: MEDIUM (eliminates scroll delay caused by event listeners)**
1335
+
1336
+ 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.
1337
+
1338
+ **Incorrect:**
1339
+
1340
+ ```typescript
1341
+ useEffect(() => {
1342
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
1343
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
1344
+
1345
+ document.addEventListener('touchstart', handleTouch)
1346
+ document.addEventListener('wheel', handleWheel)
1347
+
1348
+ return () => {
1349
+ document.removeEventListener('touchstart', handleTouch)
1350
+ document.removeEventListener('wheel', handleWheel)
1351
+ }
1352
+ }, [])
1353
+ ```
1354
+
1355
+ **Correct:**
1356
+
1357
+ ```typescript
1358
+ useEffect(() => {
1359
+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)
1360
+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)
1361
+
1362
+ document.addEventListener('touchstart', handleTouch, { passive: true })
1363
+ document.addEventListener('wheel', handleWheel, { passive: true })
1364
+
1365
+ return () => {
1366
+ document.removeEventListener('touchstart', handleTouch)
1367
+ document.removeEventListener('wheel', handleWheel)
1368
+ }
1369
+ }, [])
1370
+ ```
1371
+
1372
+ **Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
1373
+
1374
+ **Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
1375
+
1376
+ ### 4.3 Use SWR for Automatic Deduplication
1377
+
1378
+ **Impact: MEDIUM-HIGH (automatic deduplication)**
1379
+
1380
+ SWR enables request deduplication, caching, and revalidation across component instances.
1381
+
1382
+ **Incorrect: no deduplication, each instance fetches**
1383
+
1384
+ ```tsx
1385
+ function UserList() {
1386
+ const [users, setUsers] = useState([])
1387
+ useEffect(() => {
1388
+ fetch('/api/users')
1389
+ .then(r => r.json())
1390
+ .then(setUsers)
1391
+ }, [])
1392
+ }
1393
+ ```
1394
+
1395
+ **Correct: multiple instances share one request**
1396
+
1397
+ ```tsx
1398
+ import useSWR from 'swr'
1399
+
1400
+ function UserList() {
1401
+ const { data: users } = useSWR('/api/users', fetcher)
1402
+ }
1403
+ ```
1404
+
1405
+ **For immutable data:**
1406
+
1407
+ ```tsx
1408
+ import { useImmutableSWR } from '@/lib/swr'
1409
+
1410
+ function StaticContent() {
1411
+ const { data } = useImmutableSWR('/api/config', fetcher)
1412
+ }
1413
+ ```
1414
+
1415
+ **For mutations:**
1416
+
1417
+ ```tsx
1418
+ import { useSWRMutation } from 'swr/mutation'
1419
+
1420
+ function UpdateButton() {
1421
+ const { trigger } = useSWRMutation('/api/user', updateUser)
1422
+ return <button onClick={() => trigger()}>Update</button>
1423
+ }
1424
+ ```
1425
+
1426
+ Reference: [https://swr.vercel.app](https://swr.vercel.app)
1427
+
1428
+ ### 4.4 Version and Minimize localStorage Data
1429
+
1430
+ **Impact: MEDIUM (prevents schema conflicts, reduces storage size)**
1431
+
1432
+ Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
1433
+
1434
+ **Incorrect:**
1435
+
1436
+ ```typescript
1437
+ // No version, stores everything, no error handling
1438
+ localStorage.setItem('userConfig', JSON.stringify(fullUserObject))
1439
+ const data = localStorage.getItem('userConfig')
1440
+ ```
1441
+
1442
+ **Correct:**
1443
+
1444
+ ```typescript
1445
+ const VERSION = 'v2'
1446
+
1447
+ function saveConfig(config: { theme: string; language: string }) {
1448
+ try {
1449
+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))
1450
+ } catch {
1451
+ // Throws in incognito/private browsing, quota exceeded, or disabled
1452
+ }
1453
+ }
1454
+
1455
+ function loadConfig() {
1456
+ try {
1457
+ const data = localStorage.getItem(`userConfig:${VERSION}`)
1458
+ return data ? JSON.parse(data) : null
1459
+ } catch {
1460
+ return null
1461
+ }
1462
+ }
1463
+
1464
+ // Migration from v1 to v2
1465
+ function migrate() {
1466
+ try {
1467
+ const v1 = localStorage.getItem('userConfig:v1')
1468
+ if (v1) {
1469
+ const old = JSON.parse(v1)
1470
+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })
1471
+ localStorage.removeItem('userConfig:v1')
1472
+ }
1473
+ } catch {}
1474
+ }
1475
+ ```
1476
+
1477
+ **Store minimal fields from server responses:**
1478
+
1479
+ ```typescript
1480
+ // User object has 20+ fields, only store what UI needs
1481
+ function cachePrefs(user: FullUser) {
1482
+ try {
1483
+ localStorage.setItem('prefs:v1', JSON.stringify({
1484
+ theme: user.preferences.theme,
1485
+ notifications: user.preferences.notifications
1486
+ }))
1487
+ } catch {}
1488
+ }
1489
+ ```
1490
+
1491
+ **Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
1492
+
1493
+ **Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
1494
+
1495
+ ---
1496
+
1497
+ ## 5. Re-render Optimization
1498
+
1499
+ **Impact: MEDIUM**
1500
+
1501
+ Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
1502
+
1503
+ ### 5.1 Calculate Derived State During Rendering
1504
+
1505
+ **Impact: MEDIUM (avoids redundant renders and state drift)**
1506
+
1507
+ 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.
1508
+
1509
+ **Incorrect: redundant state and effect**
1510
+
1511
+ ```tsx
1512
+ function Form() {
1513
+ const [firstName, setFirstName] = useState('First')
1514
+ const [lastName, setLastName] = useState('Last')
1515
+ const [fullName, setFullName] = useState('')
1516
+
1517
+ useEffect(() => {
1518
+ setFullName(firstName + ' ' + lastName)
1519
+ }, [firstName, lastName])
1520
+
1521
+ return <p>{fullName}</p>
1522
+ }
1523
+ ```
1524
+
1525
+ **Correct: derive during render**
1526
+
1527
+ ```tsx
1528
+ function Form() {
1529
+ const [firstName, setFirstName] = useState('First')
1530
+ const [lastName, setLastName] = useState('Last')
1531
+ const fullName = firstName + ' ' + lastName
1532
+
1533
+ return <p>{fullName}</p>
1534
+ }
1535
+ ```
1536
+
1537
+ Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect)
1538
+
1539
+ ### 5.2 Defer State Reads to Usage Point
1540
+
1541
+ **Impact: MEDIUM (avoids unnecessary subscriptions)**
1542
+
1543
+ Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
1544
+
1545
+ **Incorrect: subscribes to all searchParams changes**
1546
+
1547
+ ```tsx
1548
+ function ShareButton({ chatId }: { chatId: string }) {
1549
+ const searchParams = useSearchParams()
1550
+
1551
+ const handleShare = () => {
1552
+ const ref = searchParams.get('ref')
1553
+ shareChat(chatId, { ref })
1554
+ }
1555
+
1556
+ return <button onClick={handleShare}>Share</button>
1557
+ }
1558
+ ```
1559
+
1560
+ **Correct: reads on demand, no subscription**
1561
+
1562
+ ```tsx
1563
+ function ShareButton({ chatId }: { chatId: string }) {
1564
+ const handleShare = () => {
1565
+ const params = new URLSearchParams(window.location.search)
1566
+ const ref = params.get('ref')
1567
+ shareChat(chatId, { ref })
1568
+ }
1569
+
1570
+ return <button onClick={handleShare}>Share</button>
1571
+ }
1572
+ ```
1573
+
1574
+ ### 5.3 Do not wrap a simple expression with a primitive result type in useMemo
1575
+
1576
+ **Impact: LOW-MEDIUM (wasted computation on every render)**
1577
+
1578
+ 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`.
1579
+
1580
+ Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
1581
+
1582
+ **Incorrect:**
1583
+
1584
+ ```tsx
1585
+ function Header({ user, notifications }: Props) {
1586
+ const isLoading = useMemo(() => {
1587
+ return user.isLoading || notifications.isLoading
1588
+ }, [user.isLoading, notifications.isLoading])
1589
+
1590
+ if (isLoading) return <Skeleton />
1591
+ // return some markup
1592
+ }
1593
+ ```
1594
+
1595
+ **Correct:**
1596
+
1597
+ ```tsx
1598
+ function Header({ user, notifications }: Props) {
1599
+ const isLoading = user.isLoading || notifications.isLoading
1600
+
1601
+ if (isLoading) return <Skeleton />
1602
+ // return some markup
1603
+ }
1604
+ ```
1605
+
1606
+ ### 5.4 Don't Define Components Inside Components
1607
+
1608
+ **Impact: HIGH (prevents remount on every render)**
1609
+
1610
+ Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
1611
+
1612
+ A common reason developers do this is to access parent variables without passing props. Always pass props instead.
1613
+
1614
+ **Incorrect: remounts on every render**
1615
+
1616
+ ```tsx
1617
+ function UserProfile({ user, theme }) {
1618
+ // Defined inside to access `theme` - BAD
1619
+ const Avatar = () => (
1620
+ <img
1621
+ src={user.avatarUrl}
1622
+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
1623
+ />
1624
+ )
1625
+
1626
+ // Defined inside to access `user` - BAD
1627
+ const Stats = () => (
1628
+ <div>
1629
+ <span>{user.followers} followers</span>
1630
+ <span>{user.posts} posts</span>
1631
+ </div>
1632
+ )
1633
+
1634
+ return (
1635
+ <div>
1636
+ <Avatar />
1637
+ <Stats />
1638
+ </div>
1639
+ )
1640
+ }
1641
+ ```
1642
+
1643
+ Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
1644
+
1645
+ **Correct: pass props instead**
1646
+
1647
+ ```tsx
1648
+ function Avatar({ src, theme }: { src: string; theme: string }) {
1649
+ return (
1650
+ <img
1651
+ src={src}
1652
+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}
1653
+ />
1654
+ )
1655
+ }
1656
+
1657
+ function Stats({ followers, posts }: { followers: number; posts: number }) {
1658
+ return (
1659
+ <div>
1660
+ <span>{followers} followers</span>
1661
+ <span>{posts} posts</span>
1662
+ </div>
1663
+ )
1664
+ }
1665
+
1666
+ function UserProfile({ user, theme }) {
1667
+ return (
1668
+ <div>
1669
+ <Avatar src={user.avatarUrl} theme={theme} />
1670
+ <Stats followers={user.followers} posts={user.posts} />
1671
+ </div>
1672
+ )
1673
+ }
1674
+ ```
1675
+
1676
+ **Symptoms of this bug:**
1677
+
1678
+ - Input fields lose focus on every keystroke
1679
+
1680
+ - Animations restart unexpectedly
1681
+
1682
+ - `useEffect` cleanup/setup runs on every parent render
1683
+
1684
+ - Scroll position resets inside the component
1685
+
1686
+ ### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant
1687
+
1688
+ **Impact: MEDIUM (restores memoization by using a constant for default value)**
1689
+
1690
+ 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()`.
1691
+
1692
+ To address this issue, extract the default value into a constant.
1693
+
1694
+ **Incorrect: `onClick` has different values on every rerender**
1695
+
1696
+ ```tsx
1697
+ const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
1698
+ // ...
1699
+ })
1700
+
1701
+ // Used without optional onClick
1702
+ <UserAvatar />
1703
+ ```
1704
+
1705
+ **Correct: stable default value**
1706
+
1707
+ ```tsx
1708
+ const NOOP = () => {};
1709
+
1710
+ const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
1711
+ // ...
1712
+ })
1713
+
1714
+ // Used without optional onClick
1715
+ <UserAvatar />
1716
+ ```
1717
+
1718
+ ### 5.6 Extract to Memoized Components
1719
+
1720
+ **Impact: MEDIUM (enables early returns)**
1721
+
1722
+ Extract expensive work into memoized components to enable early returns before computation.
1723
+
1724
+ **Incorrect: computes avatar even when loading**
1725
+
1726
+ ```tsx
1727
+ function Profile({ user, loading }: Props) {
1728
+ const avatar = useMemo(() => {
1729
+ const id = computeAvatarId(user)
1730
+ return <Avatar id={id} />
1731
+ }, [user])
1732
+
1733
+ if (loading) return <Skeleton />
1734
+ return <div>{avatar}</div>
1735
+ }
1736
+ ```
1737
+
1738
+ **Correct: skips computation when loading**
1739
+
1740
+ ```tsx
1741
+ const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
1742
+ const id = useMemo(() => computeAvatarId(user), [user])
1743
+ return <Avatar id={id} />
1744
+ })
1745
+
1746
+ function Profile({ user, loading }: Props) {
1747
+ if (loading) return <Skeleton />
1748
+ return (
1749
+ <div>
1750
+ <UserAvatar user={user} />
1751
+ </div>
1752
+ )
1753
+ }
1754
+ ```
1755
+
1756
+ **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.
1757
+
1758
+ ### 5.7 Narrow Effect Dependencies
1759
+
1760
+ **Impact: LOW (minimizes effect re-runs)**
1761
+
1762
+ Specify primitive dependencies instead of objects to minimize effect re-runs.
1763
+
1764
+ **Incorrect: re-runs on any user field change**
1765
+
1766
+ ```tsx
1767
+ useEffect(() => {
1768
+ console.log(user.id)
1769
+ }, [user])
1770
+ ```
1771
+
1772
+ **Correct: re-runs only when id changes**
1773
+
1774
+ ```tsx
1775
+ useEffect(() => {
1776
+ console.log(user.id)
1777
+ }, [user.id])
1778
+ ```
1779
+
1780
+ **For derived state, compute outside effect:**
1781
+
1782
+ ```tsx
1783
+ // Incorrect: runs on width=767, 766, 765...
1784
+ useEffect(() => {
1785
+ if (width < 768) {
1786
+ enableMobileMode()
1787
+ }
1788
+ }, [width])
1789
+
1790
+ // Correct: runs only on boolean transition
1791
+ const isMobile = width < 768
1792
+ useEffect(() => {
1793
+ if (isMobile) {
1794
+ enableMobileMode()
1795
+ }
1796
+ }, [isMobile])
1797
+ ```
1798
+
1799
+ ### 5.8 Put Interaction Logic in Event Handlers
1800
+
1801
+ **Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**
1802
+
1803
+ 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.
1804
+
1805
+ **Incorrect: event modeled as state + effect**
1806
+
1807
+ ```tsx
1808
+ function Form() {
1809
+ const [submitted, setSubmitted] = useState(false)
1810
+ const theme = useContext(ThemeContext)
1811
+
1812
+ useEffect(() => {
1813
+ if (submitted) {
1814
+ post('/api/register')
1815
+ showToast('Registered', theme)
1816
+ }
1817
+ }, [submitted, theme])
1818
+
1819
+ return <button onClick={() => setSubmitted(true)}>Submit</button>
1820
+ }
1821
+ ```
1822
+
1823
+ **Correct: do it in the handler**
1824
+
1825
+ ```tsx
1826
+ function Form() {
1827
+ const theme = useContext(ThemeContext)
1828
+
1829
+ function handleSubmit() {
1830
+ post('/api/register')
1831
+ showToast('Registered', theme)
1832
+ }
1833
+
1834
+ return <button onClick={handleSubmit}>Submit</button>
1835
+ }
1836
+ ```
1837
+
1838
+ Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
1839
+
1840
+ ### 5.9 Split Combined Hook Computations
1841
+
1842
+ **Impact: MEDIUM (avoids recomputing independent steps)**
1843
+
1844
+ When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
1845
+
1846
+ **Incorrect: changing `sortOrder` recomputes filtering**
1847
+
1848
+ ```tsx
1849
+ const sortedProducts = useMemo(() => {
1850
+ const filtered = products.filter((p) => p.category === category)
1851
+ const sorted = filtered.toSorted((a, b) =>
1852
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
1853
+ )
1854
+ return sorted
1855
+ }, [products, category, sortOrder])
1856
+ ```
1857
+
1858
+ **Correct: filtering only recomputes when products or category change**
1859
+
1860
+ ```tsx
1861
+ const filteredProducts = useMemo(
1862
+ () => products.filter((p) => p.category === category),
1863
+ [products, category]
1864
+ )
1865
+
1866
+ const sortedProducts = useMemo(
1867
+ () =>
1868
+ filteredProducts.toSorted((a, b) =>
1869
+ sortOrder === "asc" ? a.price - b.price : b.price - a.price
1870
+ ),
1871
+ [filteredProducts, sortOrder]
1872
+ )
1873
+ ```
1874
+
1875
+ This pattern also applies to `useEffect` when combining unrelated side effects:
1876
+
1877
+ **Incorrect: both effects run when either dependency changes**
1878
+
1879
+ ```tsx
1880
+ useEffect(() => {
1881
+ analytics.trackPageView(pathname)
1882
+ document.title = `${pageTitle} | My App`
1883
+ }, [pathname, pageTitle])
1884
+ ```
1885
+
1886
+ **Correct: effects run independently**
1887
+
1888
+ ```tsx
1889
+ useEffect(() => {
1890
+ analytics.trackPageView(pathname)
1891
+ }, [pathname])
1892
+
1893
+ useEffect(() => {
1894
+ document.title = `${pageTitle} | My App`
1895
+ }, [pageTitle])
1896
+ ```
1897
+
1898
+ **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
1899
+
1900
+ ### 5.10 Subscribe to Derived State
1901
+
1902
+ **Impact: MEDIUM (reduces re-render frequency)**
1903
+
1904
+ Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
1905
+
1906
+ **Incorrect: re-renders on every pixel change**
1907
+
1908
+ ```tsx
1909
+ function Sidebar() {
1910
+ const width = useWindowWidth() // updates continuously
1911
+ const isMobile = width < 768
1912
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
1913
+ }
1914
+ ```
1915
+
1916
+ **Correct: re-renders only when boolean changes**
1917
+
1918
+ ```tsx
1919
+ function Sidebar() {
1920
+ const isMobile = useMediaQuery('(max-width: 767px)')
1921
+ return <nav className={isMobile ? 'mobile' : 'desktop'} />
1922
+ }
1923
+ ```
1924
+
1925
+ ### 5.11 Use Functional setState Updates
1926
+
1927
+ **Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**
1928
+
1929
+ 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.
1930
+
1931
+ **Incorrect: requires state as dependency**
1932
+
1933
+ ```tsx
1934
+ function TodoList() {
1935
+ const [items, setItems] = useState(initialItems)
1936
+
1937
+ // Callback must depend on items, recreated on every items change
1938
+ const addItems = useCallback((newItems: Item[]) => {
1939
+ setItems([...items, ...newItems])
1940
+ }, [items]) // ❌ items dependency causes recreations
1941
+
1942
+ // Risk of stale closure if dependency is forgotten
1943
+ const removeItem = useCallback((id: string) => {
1944
+ setItems(items.filter(item => item.id !== id))
1945
+ }, []) // ❌ Missing items dependency - will use stale items!
1946
+
1947
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
1948
+ }
1949
+ ```
1950
+
1951
+ 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.
1952
+
1953
+ **Correct: stable callbacks, no stale closures**
1954
+
1955
+ ```tsx
1956
+ function TodoList() {
1957
+ const [items, setItems] = useState(initialItems)
1958
+
1959
+ // Stable callback, never recreated
1960
+ const addItems = useCallback((newItems: Item[]) => {
1961
+ setItems(curr => [...curr, ...newItems])
1962
+ }, []) // ✅ No dependencies needed
1963
+
1964
+ // Always uses latest state, no stale closure risk
1965
+ const removeItem = useCallback((id: string) => {
1966
+ setItems(curr => curr.filter(item => item.id !== id))
1967
+ }, []) // ✅ Safe and stable
1968
+
1969
+ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
1970
+ }
1971
+ ```
1972
+
1973
+ **Benefits:**
1974
+
1975
+ 1. **Stable callback references** - Callbacks don't need to be recreated when state changes
1976
+
1977
+ 2. **No stale closures** - Always operates on the latest state value
1978
+
1979
+ 3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
1980
+
1981
+ 4. **Prevents bugs** - Eliminates the most common source of React closure bugs
1982
+
1983
+ **When to use functional updates:**
1984
+
1985
+ - Any setState that depends on the current state value
1986
+
1987
+ - Inside useCallback/useMemo when state is needed
1988
+
1989
+ - Event handlers that reference state
1990
+
1991
+ - Async operations that update state
1992
+
1993
+ **When direct updates are fine:**
1994
+
1995
+ - Setting state to a static value: `setCount(0)`
1996
+
1997
+ - Setting state from props/arguments only: `setName(newName)`
1998
+
1999
+ - State doesn't depend on previous value
2000
+
2001
+ **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.
2002
+
2003
+ ### 5.12 Use Lazy State Initialization
2004
+
2005
+ **Impact: MEDIUM (wasted computation on every render)**
2006
+
2007
+ 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.
2008
+
2009
+ **Incorrect: runs on every render**
2010
+
2011
+ ```tsx
2012
+ function FilteredList({ items }: { items: Item[] }) {
2013
+ // buildSearchIndex() runs on EVERY render, even after initialization
2014
+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
2015
+ const [query, setQuery] = useState('')
2016
+
2017
+ // When query changes, buildSearchIndex runs again unnecessarily
2018
+ return <SearchResults index={searchIndex} query={query} />
2019
+ }
2020
+
2021
+ function UserProfile() {
2022
+ // JSON.parse runs on every render
2023
+ const [settings, setSettings] = useState(
2024
+ JSON.parse(localStorage.getItem('settings') || '{}')
2025
+ )
2026
+
2027
+ return <SettingsForm settings={settings} onChange={setSettings} />
2028
+ }
2029
+ ```
2030
+
2031
+ **Correct: runs only once**
2032
+
2033
+ ```tsx
2034
+ function FilteredList({ items }: { items: Item[] }) {
2035
+ // buildSearchIndex() runs ONLY on initial render
2036
+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
2037
+ const [query, setQuery] = useState('')
2038
+
2039
+ return <SearchResults index={searchIndex} query={query} />
2040
+ }
2041
+
2042
+ function UserProfile() {
2043
+ // JSON.parse runs only on initial render
2044
+ const [settings, setSettings] = useState(() => {
2045
+ const stored = localStorage.getItem('settings')
2046
+ return stored ? JSON.parse(stored) : {}
2047
+ })
2048
+
2049
+ return <SettingsForm settings={settings} onChange={setSettings} />
2050
+ }
2051
+ ```
2052
+
2053
+ Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
2054
+
2055
+ For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
2056
+
2057
+ ### 5.13 Use Transitions for Non-Urgent Updates
2058
+
2059
+ **Impact: MEDIUM (maintains UI responsiveness)**
2060
+
2061
+ Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
2062
+
2063
+ **Incorrect: blocks UI on every scroll**
2064
+
2065
+ ```tsx
2066
+ function ScrollTracker() {
2067
+ const [scrollY, setScrollY] = useState(0)
2068
+ useEffect(() => {
2069
+ const handler = () => setScrollY(window.scrollY)
2070
+ window.addEventListener('scroll', handler, { passive: true })
2071
+ return () => window.removeEventListener('scroll', handler)
2072
+ }, [])
2073
+ }
2074
+ ```
2075
+
2076
+ **Correct: non-blocking updates**
2077
+
2078
+ ```tsx
2079
+ import { startTransition } from 'react'
2080
+
2081
+ function ScrollTracker() {
2082
+ const [scrollY, setScrollY] = useState(0)
2083
+ useEffect(() => {
2084
+ const handler = () => {
2085
+ startTransition(() => setScrollY(window.scrollY))
2086
+ }
2087
+ window.addEventListener('scroll', handler, { passive: true })
2088
+ return () => window.removeEventListener('scroll', handler)
2089
+ }, [])
2090
+ }
2091
+ ```
2092
+
2093
+ ### 5.14 Use useDeferredValue for Expensive Derived Renders
2094
+
2095
+ **Impact: MEDIUM (keeps input responsive during heavy computation)**
2096
+
2097
+ When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
2098
+
2099
+ **Incorrect: input feels laggy while filtering**
2100
+
2101
+ ```tsx
2102
+ function Search({ items }: { items: Item[] }) {
2103
+ const [query, setQuery] = useState('')
2104
+ const filtered = items.filter(item => fuzzyMatch(item, query))
2105
+
2106
+ return (
2107
+ <>
2108
+ <input value={query} onChange={e => setQuery(e.target.value)} />
2109
+ <ResultsList results={filtered} />
2110
+ </>
2111
+ )
2112
+ }
2113
+ ```
2114
+
2115
+ **Correct: input stays snappy, results render when ready**
2116
+
2117
+ ```tsx
2118
+ function Search({ items }: { items: Item[] }) {
2119
+ const [query, setQuery] = useState('')
2120
+ const deferredQuery = useDeferredValue(query)
2121
+ const filtered = useMemo(
2122
+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),
2123
+ [items, deferredQuery]
2124
+ )
2125
+ const isStale = query !== deferredQuery
2126
+
2127
+ return (
2128
+ <>
2129
+ <input value={query} onChange={e => setQuery(e.target.value)} />
2130
+ <div style={{ opacity: isStale ? 0.7 : 1 }}>
2131
+ <ResultsList results={filtered} />
2132
+ </div>
2133
+ </>
2134
+ )
2135
+ }
2136
+ ```
2137
+
2138
+ **When to use:**
2139
+
2140
+ - Filtering/searching large lists
2141
+
2142
+ - Expensive visualizations (charts, graphs) reacting to input
2143
+
2144
+ - Any derived state that causes noticeable render delays
2145
+
2146
+ **Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.
2147
+
2148
+ Reference: [https://react.dev/reference/react/useDeferredValue](https://react.dev/reference/react/useDeferredValue)
2149
+
2150
+ ### 5.15 Use useRef for Transient Values
2151
+
2152
+ **Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**
2153
+
2154
+ 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.
2155
+
2156
+ **Incorrect: renders every update**
2157
+
2158
+ ```tsx
2159
+ function Tracker() {
2160
+ const [lastX, setLastX] = useState(0)
2161
+
2162
+ useEffect(() => {
2163
+ const onMove = (e: MouseEvent) => setLastX(e.clientX)
2164
+ window.addEventListener('mousemove', onMove)
2165
+ return () => window.removeEventListener('mousemove', onMove)
2166
+ }, [])
2167
+
2168
+ return (
2169
+ <div
2170
+ style={{
2171
+ position: 'fixed',
2172
+ top: 0,
2173
+ left: lastX,
2174
+ width: 8,
2175
+ height: 8,
2176
+ background: 'black',
2177
+ }}
2178
+ />
2179
+ )
2180
+ }
2181
+ ```
2182
+
2183
+ **Correct: no re-render for tracking**
2184
+
2185
+ ```tsx
2186
+ function Tracker() {
2187
+ const lastXRef = useRef(0)
2188
+ const dotRef = useRef<HTMLDivElement>(null)
2189
+
2190
+ useEffect(() => {
2191
+ const onMove = (e: MouseEvent) => {
2192
+ lastXRef.current = e.clientX
2193
+ const node = dotRef.current
2194
+ if (node) {
2195
+ node.style.transform = `translateX(${e.clientX}px)`
2196
+ }
2197
+ }
2198
+ window.addEventListener('mousemove', onMove)
2199
+ return () => window.removeEventListener('mousemove', onMove)
2200
+ }, [])
2201
+
2202
+ return (
2203
+ <div
2204
+ ref={dotRef}
2205
+ style={{
2206
+ position: 'fixed',
2207
+ top: 0,
2208
+ left: 0,
2209
+ width: 8,
2210
+ height: 8,
2211
+ background: 'black',
2212
+ transform: 'translateX(0px)',
2213
+ }}
2214
+ />
2215
+ )
2216
+ }
2217
+ ```
2218
+
2219
+ ---
2220
+
2221
+ ## 6. Rendering Performance
2222
+
2223
+ **Impact: MEDIUM**
2224
+
2225
+ Optimizing the rendering process reduces the work the browser needs to do.
2226
+
2227
+ ### 6.1 Animate SVG Wrapper Instead of SVG Element
2228
+
2229
+ **Impact: LOW (enables hardware acceleration)**
2230
+
2231
+ Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
2232
+
2233
+ **Incorrect: animating SVG directly - no hardware acceleration**
2234
+
2235
+ ```tsx
2236
+ function LoadingSpinner() {
2237
+ return (
2238
+ <svg
2239
+ className="animate-spin"
2240
+ width="24"
2241
+ height="24"
2242
+ viewBox="0 0 24 24"
2243
+ >
2244
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
2245
+ </svg>
2246
+ )
2247
+ }
2248
+ ```
2249
+
2250
+ **Correct: animating wrapper div - hardware accelerated**
2251
+
2252
+ ```tsx
2253
+ function LoadingSpinner() {
2254
+ return (
2255
+ <div className="animate-spin">
2256
+ <svg
2257
+ width="24"
2258
+ height="24"
2259
+ viewBox="0 0 24 24"
2260
+ >
2261
+ <circle cx="12" cy="12" r="10" stroke="currentColor" />
2262
+ </svg>
2263
+ </div>
2264
+ )
2265
+ }
2266
+ ```
2267
+
2268
+ 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.
2269
+
2270
+ ### 6.2 CSS content-visibility for Long Lists
2271
+
2272
+ **Impact: HIGH (faster initial render)**
2273
+
2274
+ Apply `content-visibility: auto` to defer off-screen rendering.
2275
+
2276
+ **CSS:**
2277
+
2278
+ ```css
2279
+ .message-item {
2280
+ content-visibility: auto;
2281
+ contain-intrinsic-size: 0 80px;
2282
+ }
2283
+ ```
2284
+
2285
+ **Example:**
2286
+
2287
+ ```tsx
2288
+ function MessageList({ messages }: { messages: Message[] }) {
2289
+ return (
2290
+ <div className="overflow-y-auto h-screen">
2291
+ {messages.map(msg => (
2292
+ <div key={msg.id} className="message-item">
2293
+ <Avatar user={msg.author} />
2294
+ <div>{msg.content}</div>
2295
+ </div>
2296
+ ))}
2297
+ </div>
2298
+ )
2299
+ }
2300
+ ```
2301
+
2302
+ For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
2303
+
2304
+ ### 6.3 Hoist Static JSX Elements
2305
+
2306
+ **Impact: LOW (avoids re-creation)**
2307
+
2308
+ Extract static JSX outside components to avoid re-creation.
2309
+
2310
+ **Incorrect: recreates element every render**
2311
+
2312
+ ```tsx
2313
+ function LoadingSkeleton() {
2314
+ return <div className="animate-pulse h-20 bg-gray-200" />
2315
+ }
2316
+
2317
+ function Container() {
2318
+ return (
2319
+ <div>
2320
+ {loading && <LoadingSkeleton />}
2321
+ </div>
2322
+ )
2323
+ }
2324
+ ```
2325
+
2326
+ **Correct: reuses same element**
2327
+
2328
+ ```tsx
2329
+ const loadingSkeleton = (
2330
+ <div className="animate-pulse h-20 bg-gray-200" />
2331
+ )
2332
+
2333
+ function Container() {
2334
+ return (
2335
+ <div>
2336
+ {loading && loadingSkeleton}
2337
+ </div>
2338
+ )
2339
+ }
2340
+ ```
2341
+
2342
+ This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
2343
+
2344
+ **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.
2345
+
2346
+ ### 6.4 Optimize SVG Precision
2347
+
2348
+ **Impact: LOW (reduces file size)**
2349
+
2350
+ Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
2351
+
2352
+ **Incorrect: excessive precision**
2353
+
2354
+ ```svg
2355
+ <path d="M 10.293847 20.847362 L 30.938472 40.192837" />
2356
+ ```
2357
+
2358
+ **Correct: 1 decimal place**
2359
+
2360
+ ```svg
2361
+ <path d="M 10.3 20.8 L 30.9 40.2" />
2362
+ ```
2363
+
2364
+ **Automate with SVGO:**
2365
+
2366
+ ```bash
2367
+ npx svgo --precision=1 --multipass icon.svg
2368
+ ```
2369
+
2370
+ ### 6.5 Prevent Hydration Mismatch Without Flickering
2371
+
2372
+ **Impact: MEDIUM (avoids visual flicker and hydration errors)**
2373
+
2374
+ 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.
2375
+
2376
+ **Incorrect: breaks SSR**
2377
+
2378
+ ```tsx
2379
+ function ThemeWrapper({ children }: { children: ReactNode }) {
2380
+ // localStorage is not available on server - throws error
2381
+ const theme = localStorage.getItem('theme') || 'light'
2382
+
2383
+ return (
2384
+ <div className={theme}>
2385
+ {children}
2386
+ </div>
2387
+ )
2388
+ }
2389
+ ```
2390
+
2391
+ Server-side rendering will fail because `localStorage` is undefined.
2392
+
2393
+ **Incorrect: visual flickering**
2394
+
2395
+ ```tsx
2396
+ function ThemeWrapper({ children }: { children: ReactNode }) {
2397
+ const [theme, setTheme] = useState('light')
2398
+
2399
+ useEffect(() => {
2400
+ // Runs after hydration - causes visible flash
2401
+ const stored = localStorage.getItem('theme')
2402
+ if (stored) {
2403
+ setTheme(stored)
2404
+ }
2405
+ }, [])
2406
+
2407
+ return (
2408
+ <div className={theme}>
2409
+ {children}
2410
+ </div>
2411
+ )
2412
+ }
2413
+ ```
2414
+
2415
+ Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
2416
+
2417
+ **Correct: no flicker, no hydration mismatch**
2418
+
2419
+ ```tsx
2420
+ function ThemeWrapper({ children }: { children: ReactNode }) {
2421
+ return (
2422
+ <>
2423
+ <div id="theme-wrapper">
2424
+ {children}
2425
+ </div>
2426
+ <script
2427
+ dangerouslySetInnerHTML={{
2428
+ __html: `
2429
+ (function() {
2430
+ try {
2431
+ var theme = localStorage.getItem('theme') || 'light';
2432
+ var el = document.getElementById('theme-wrapper');
2433
+ if (el) el.className = theme;
2434
+ } catch (e) {}
2435
+ })();
2436
+ `,
2437
+ }}
2438
+ />
2439
+ </>
2440
+ )
2441
+ }
2442
+ ```
2443
+
2444
+ The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
2445
+
2446
+ 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.
2447
+
2448
+ ### 6.6 Suppress Expected Hydration Mismatches
2449
+
2450
+ **Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)**
2451
+
2452
+ 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.
2453
+
2454
+ **Incorrect: known mismatch warnings**
2455
+
2456
+ ```tsx
2457
+ function Timestamp() {
2458
+ return <span>{new Date().toLocaleString()}</span>
2459
+ }
2460
+ ```
2461
+
2462
+ **Correct: suppress expected mismatch only**
2463
+
2464
+ ```tsx
2465
+ function Timestamp() {
2466
+ return (
2467
+ <span suppressHydrationWarning>
2468
+ {new Date().toLocaleString()}
2469
+ </span>
2470
+ )
2471
+ }
2472
+ ```
2473
+
2474
+ ### 6.7 Use Activity Component for Show/Hide
2475
+
2476
+ **Impact: MEDIUM (preserves state/DOM)**
2477
+
2478
+ Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
2479
+
2480
+ **Usage:**
2481
+
2482
+ ```tsx
2483
+ import { Activity } from 'react'
2484
+
2485
+ function Dropdown({ isOpen }: Props) {
2486
+ return (
2487
+ <Activity mode={isOpen ? 'visible' : 'hidden'}>
2488
+ <ExpensiveMenu />
2489
+ </Activity>
2490
+ )
2491
+ }
2492
+ ```
2493
+
2494
+ Avoids expensive re-renders and state loss.
2495
+
2496
+ ### 6.8 Use defer or async on Script Tags
2497
+
2498
+ **Impact: HIGH (eliminates render-blocking)**
2499
+
2500
+ Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
2501
+
2502
+ - **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
2503
+
2504
+ - **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
2505
+
2506
+ Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
2507
+
2508
+ **Incorrect: blocks rendering**
2509
+
2510
+ ```tsx
2511
+ export default function Document() {
2512
+ return (
2513
+ <html>
2514
+ <head>
2515
+ <script src="https://example.com/analytics.js" />
2516
+ <script src="/scripts/utils.js" />
2517
+ </head>
2518
+ <body>{/* content */}</body>
2519
+ </html>
2520
+ )
2521
+ }
2522
+ ```
2523
+
2524
+ **Correct: non-blocking**
2525
+
2526
+ ```tsx
2527
+ import Script from 'next/script'
2528
+
2529
+ export default function Page() {
2530
+ return (
2531
+ <>
2532
+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />
2533
+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />
2534
+ </>
2535
+ )
2536
+ }
2537
+ ```
2538
+
2539
+ **Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
2540
+
2541
+ Reference: [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
2542
+
2543
+ ### 6.9 Use Explicit Conditional Rendering
2544
+
2545
+ **Impact: LOW (prevents rendering 0 or NaN)**
2546
+
2547
+ Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
2548
+
2549
+ **Incorrect: renders "0" when count is 0**
2550
+
2551
+ ```tsx
2552
+ function Badge({ count }: { count: number }) {
2553
+ return (
2554
+ <div>
2555
+ {count && <span className="badge">{count}</span>}
2556
+ </div>
2557
+ )
2558
+ }
2559
+
2560
+ // When count = 0, renders: <div>0</div>
2561
+ // When count = 5, renders: <div><span class="badge">5</span></div>
2562
+ ```
2563
+
2564
+ **Correct: renders nothing when count is 0**
2565
+
2566
+ ```tsx
2567
+ function Badge({ count }: { count: number }) {
2568
+ return (
2569
+ <div>
2570
+ {count > 0 ? <span className="badge">{count}</span> : null}
2571
+ </div>
2572
+ )
2573
+ }
2574
+
2575
+ // When count = 0, renders: <div></div>
2576
+ // When count = 5, renders: <div><span class="badge">5</span></div>
2577
+ ```
2578
+
2579
+ ### 6.10 Use React DOM Resource Hints
2580
+
2581
+ **Impact: HIGH (reduces load time for critical resources)**
2582
+
2583
+ React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
2584
+
2585
+ - **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
2586
+
2587
+ - **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
2588
+
2589
+ - **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
2590
+
2591
+ - **`preloadModule(href)`**: Fetch an ES module you'll use soon
2592
+
2593
+ - **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
2594
+
2595
+ - **`preinitModule(href)`**: Fetch and evaluate an ES module
2596
+
2597
+ **Example: preconnect to third-party APIs**
2598
+
2599
+ ```tsx
2600
+ import { preconnect, prefetchDNS } from 'react-dom'
2601
+
2602
+ export default function App() {
2603
+ prefetchDNS('https://analytics.example.com')
2604
+ preconnect('https://api.example.com')
2605
+
2606
+ return <main>{/* content */}</main>
2607
+ }
2608
+ ```
2609
+
2610
+ **Example: preload critical fonts and styles**
2611
+
2612
+ ```tsx
2613
+ import { preload, preinit } from 'react-dom'
2614
+
2615
+ export default function RootLayout({ children }) {
2616
+ // Preload font file
2617
+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })
2618
+
2619
+ // Fetch and apply critical stylesheet immediately
2620
+ preinit('/styles/critical.css', { as: 'style' })
2621
+
2622
+ return (
2623
+ <html>
2624
+ <body>{children}</body>
2625
+ </html>
2626
+ )
2627
+ }
2628
+ ```
2629
+
2630
+ **Example: preload modules for code-split routes**
2631
+
2632
+ ```tsx
2633
+ import { preloadModule, preinitModule } from 'react-dom'
2634
+
2635
+ function Navigation() {
2636
+ const preloadDashboard = () => {
2637
+ preloadModule('/dashboard.js', { as: 'script' })
2638
+ }
2639
+
2640
+ return (
2641
+ <nav>
2642
+ <a href="/dashboard" onMouseEnter={preloadDashboard}>
2643
+ Dashboard
2644
+ </a>
2645
+ </nav>
2646
+ )
2647
+ }
2648
+ ```
2649
+
2650
+ **When to use each:**
2651
+
2652
+ | API | Use case |
2653
+
2654
+ |-----|----------|
2655
+
2656
+ | `prefetchDNS` | Third-party domains you'll connect to later |
2657
+
2658
+ | `preconnect` | APIs or CDNs you'll fetch from immediately |
2659
+
2660
+ | `preload` | Critical resources needed for current page |
2661
+
2662
+ | `preloadModule` | JS modules for likely next navigation |
2663
+
2664
+ | `preinit` | Stylesheets/scripts that must execute early |
2665
+
2666
+ | `preinitModule` | ES modules that must execute early |
2667
+
2668
+ Reference: [https://react.dev/reference/react-dom#resource-preloading-apis](https://react.dev/reference/react-dom#resource-preloading-apis)
2669
+
2670
+ ### 6.11 Use useTransition Over Manual Loading States
2671
+
2672
+ **Impact: LOW (reduces re-renders and improves code clarity)**
2673
+
2674
+ Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.
2675
+
2676
+ **Incorrect: manual loading state**
2677
+
2678
+ ```tsx
2679
+ function SearchResults() {
2680
+ const [query, setQuery] = useState('')
2681
+ const [results, setResults] = useState([])
2682
+ const [isLoading, setIsLoading] = useState(false)
2683
+
2684
+ const handleSearch = async (value: string) => {
2685
+ setIsLoading(true)
2686
+ setQuery(value)
2687
+ const data = await fetchResults(value)
2688
+ setResults(data)
2689
+ setIsLoading(false)
2690
+ }
2691
+
2692
+ return (
2693
+ <>
2694
+ <input onChange={(e) => handleSearch(e.target.value)} />
2695
+ {isLoading && <Spinner />}
2696
+ <ResultsList results={results} />
2697
+ </>
2698
+ )
2699
+ }
2700
+ ```
2701
+
2702
+ **Correct: useTransition with built-in pending state**
2703
+
2704
+ ```tsx
2705
+ import { useTransition, useState } from 'react'
2706
+
2707
+ function SearchResults() {
2708
+ const [query, setQuery] = useState('')
2709
+ const [results, setResults] = useState([])
2710
+ const [isPending, startTransition] = useTransition()
2711
+
2712
+ const handleSearch = (value: string) => {
2713
+ setQuery(value) // Update input immediately
2714
+
2715
+ startTransition(async () => {
2716
+ // Fetch and update results
2717
+ const data = await fetchResults(value)
2718
+ setResults(data)
2719
+ })
2720
+ }
2721
+
2722
+ return (
2723
+ <>
2724
+ <input onChange={(e) => handleSearch(e.target.value)} />
2725
+ {isPending && <Spinner />}
2726
+ <ResultsList results={results} />
2727
+ </>
2728
+ )
2729
+ }
2730
+ ```
2731
+
2732
+ **Benefits:**
2733
+
2734
+ - **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`
2735
+
2736
+ - **Error resilience**: Pending state correctly resets even if the transition throws
2737
+
2738
+ - **Better responsiveness**: Keeps the UI responsive during updates
2739
+
2740
+ - **Interrupt handling**: New transitions automatically cancel pending ones
2741
+
2742
+ Reference: [https://react.dev/reference/react/useTransition](https://react.dev/reference/react/useTransition)
2743
+
2744
+ ---
2745
+
2746
+ ## 7. JavaScript Performance
2747
+
2748
+ **Impact: LOW-MEDIUM**
2749
+
2750
+ Micro-optimizations for hot paths can add up to meaningful improvements.
2751
+
2752
+ ### 7.1 Avoid Layout Thrashing
2753
+
2754
+ **Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)**
2755
+
2756
+ 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.
2757
+
2758
+ **This is OK: browser batches style changes**
2759
+
2760
+ ```typescript
2761
+ function updateElementStyles(element: HTMLElement) {
2762
+ // Each line invalidates style, but browser batches the recalculation
2763
+ element.style.width = '100px'
2764
+ element.style.height = '200px'
2765
+ element.style.backgroundColor = 'blue'
2766
+ element.style.border = '1px solid black'
2767
+ }
2768
+ ```
2769
+
2770
+ **Incorrect: interleaved reads and writes force reflows**
2771
+
2772
+ ```typescript
2773
+ function layoutThrashing(element: HTMLElement) {
2774
+ element.style.width = '100px'
2775
+ const width = element.offsetWidth // Forces reflow
2776
+ element.style.height = '200px'
2777
+ const height = element.offsetHeight // Forces another reflow
2778
+ }
2779
+ ```
2780
+
2781
+ **Correct: batch writes, then read once**
2782
+
2783
+ ```typescript
2784
+ function updateElementStyles(element: HTMLElement) {
2785
+ // Batch all writes together
2786
+ element.style.width = '100px'
2787
+ element.style.height = '200px'
2788
+ element.style.backgroundColor = 'blue'
2789
+ element.style.border = '1px solid black'
2790
+
2791
+ // Read after all writes are done (single reflow)
2792
+ const { width, height } = element.getBoundingClientRect()
2793
+ }
2794
+ ```
2795
+
2796
+ **Correct: batch reads, then writes**
2797
+
2798
+ ```typescript
2799
+ function updateElementStyles(element: HTMLElement) {
2800
+ element.classList.add('highlighted-box')
2801
+
2802
+ const { width, height } = element.getBoundingClientRect()
2803
+ }
2804
+ ```
2805
+
2806
+ **Better: use CSS classes**
2807
+
2808
+ **React example:**
2809
+
2810
+ ```tsx
2811
+ // Incorrect: interleaving style changes with layout queries
2812
+ function Box({ isHighlighted }: { isHighlighted: boolean }) {
2813
+ const ref = useRef<HTMLDivElement>(null)
2814
+
2815
+ useEffect(() => {
2816
+ if (ref.current && isHighlighted) {
2817
+ ref.current.style.width = '100px'
2818
+ const width = ref.current.offsetWidth // Forces layout
2819
+ ref.current.style.height = '200px'
2820
+ }
2821
+ }, [isHighlighted])
2822
+
2823
+ return <div ref={ref}>Content</div>
2824
+ }
2825
+
2826
+ // Correct: toggle class
2827
+ function Box({ isHighlighted }: { isHighlighted: boolean }) {
2828
+ return (
2829
+ <div className={isHighlighted ? 'highlighted-box' : ''}>
2830
+ Content
2831
+ </div>
2832
+ )
2833
+ }
2834
+ ```
2835
+
2836
+ 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.
2837
+
2838
+ See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
2839
+
2840
+ ### 7.2 Build Index Maps for Repeated Lookups
2841
+
2842
+ **Impact: LOW-MEDIUM (1M ops to 2K ops)**
2843
+
2844
+ Multiple `.find()` calls by the same key should use a Map.
2845
+
2846
+ **Incorrect (O(n) per lookup):**
2847
+
2848
+ ```typescript
2849
+ function processOrders(orders: Order[], users: User[]) {
2850
+ return orders.map(order => ({
2851
+ ...order,
2852
+ user: users.find(u => u.id === order.userId)
2853
+ }))
2854
+ }
2855
+ ```
2856
+
2857
+ **Correct (O(1) per lookup):**
2858
+
2859
+ ```typescript
2860
+ function processOrders(orders: Order[], users: User[]) {
2861
+ const userById = new Map(users.map(u => [u.id, u]))
2862
+
2863
+ return orders.map(order => ({
2864
+ ...order,
2865
+ user: userById.get(order.userId)
2866
+ }))
2867
+ }
2868
+ ```
2869
+
2870
+ Build map once (O(n)), then all lookups are O(1).
2871
+
2872
+ For 1000 orders × 1000 users: 1M ops → 2K ops.
2873
+
2874
+ ### 7.3 Cache Property Access in Loops
2875
+
2876
+ **Impact: LOW-MEDIUM (reduces lookups)**
2877
+
2878
+ Cache object property lookups in hot paths.
2879
+
2880
+ **Incorrect: 3 lookups × N iterations**
2881
+
2882
+ ```typescript
2883
+ for (let i = 0; i < arr.length; i++) {
2884
+ process(obj.config.settings.value)
2885
+ }
2886
+ ```
2887
+
2888
+ **Correct: 1 lookup total**
2889
+
2890
+ ```typescript
2891
+ const value = obj.config.settings.value
2892
+ const len = arr.length
2893
+ for (let i = 0; i < len; i++) {
2894
+ process(value)
2895
+ }
2896
+ ```
2897
+
2898
+ ### 7.4 Cache Repeated Function Calls
2899
+
2900
+ **Impact: MEDIUM (avoid redundant computation)**
2901
+
2902
+ Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
2903
+
2904
+ **Incorrect: redundant computation**
2905
+
2906
+ ```typescript
2907
+ function ProjectList({ projects }: { projects: Project[] }) {
2908
+ return (
2909
+ <div>
2910
+ {projects.map(project => {
2911
+ // slugify() called 100+ times for same project names
2912
+ const slug = slugify(project.name)
2913
+
2914
+ return <ProjectCard key={project.id} slug={slug} />
2915
+ })}
2916
+ </div>
2917
+ )
2918
+ }
2919
+ ```
2920
+
2921
+ **Correct: cached results**
2922
+
2923
+ ```typescript
2924
+ // Module-level cache
2925
+ const slugifyCache = new Map<string, string>()
2926
+
2927
+ function cachedSlugify(text: string): string {
2928
+ if (slugifyCache.has(text)) {
2929
+ return slugifyCache.get(text)!
2930
+ }
2931
+ const result = slugify(text)
2932
+ slugifyCache.set(text, result)
2933
+ return result
2934
+ }
2935
+
2936
+ function ProjectList({ projects }: { projects: Project[] }) {
2937
+ return (
2938
+ <div>
2939
+ {projects.map(project => {
2940
+ // Computed only once per unique project name
2941
+ const slug = cachedSlugify(project.name)
2942
+
2943
+ return <ProjectCard key={project.id} slug={slug} />
2944
+ })}
2945
+ </div>
2946
+ )
2947
+ }
2948
+ ```
2949
+
2950
+ **Simpler pattern for single-value functions:**
2951
+
2952
+ ```typescript
2953
+ let isLoggedInCache: boolean | null = null
2954
+
2955
+ function isLoggedIn(): boolean {
2956
+ if (isLoggedInCache !== null) {
2957
+ return isLoggedInCache
2958
+ }
2959
+
2960
+ isLoggedInCache = document.cookie.includes('auth=')
2961
+ return isLoggedInCache
2962
+ }
2963
+
2964
+ // Clear cache when auth changes
2965
+ function onAuthChange() {
2966
+ isLoggedInCache = null
2967
+ }
2968
+ ```
2969
+
2970
+ Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
2971
+
2972
+ Reference: [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
2973
+
2974
+ ### 7.5 Cache Storage API Calls
2975
+
2976
+ **Impact: LOW-MEDIUM (reduces expensive I/O)**
2977
+
2978
+ `localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
2979
+
2980
+ **Incorrect: reads storage on every call**
2981
+
2982
+ ```typescript
2983
+ function getTheme() {
2984
+ return localStorage.getItem('theme') ?? 'light'
2985
+ }
2986
+ // Called 10 times = 10 storage reads
2987
+ ```
2988
+
2989
+ **Correct: Map cache**
2990
+
2991
+ ```typescript
2992
+ const storageCache = new Map<string, string | null>()
2993
+
2994
+ function getLocalStorage(key: string) {
2995
+ if (!storageCache.has(key)) {
2996
+ storageCache.set(key, localStorage.getItem(key))
2997
+ }
2998
+ return storageCache.get(key)
2999
+ }
3000
+
3001
+ function setLocalStorage(key: string, value: string) {
3002
+ localStorage.setItem(key, value)
3003
+ storageCache.set(key, value) // keep cache in sync
3004
+ }
3005
+ ```
3006
+
3007
+ Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
3008
+
3009
+ **Cookie caching:**
3010
+
3011
+ ```typescript
3012
+ let cookieCache: Record<string, string> | null = null
3013
+
3014
+ function getCookie(name: string) {
3015
+ if (!cookieCache) {
3016
+ cookieCache = Object.fromEntries(
3017
+ document.cookie.split('; ').map(c => c.split('='))
3018
+ )
3019
+ }
3020
+ return cookieCache[name]
3021
+ }
3022
+ ```
3023
+
3024
+ **Important: invalidate on external changes**
3025
+
3026
+ ```typescript
3027
+ window.addEventListener('storage', (e) => {
3028
+ if (e.key) storageCache.delete(e.key)
3029
+ })
3030
+
3031
+ document.addEventListener('visibilitychange', () => {
3032
+ if (document.visibilityState === 'visible') {
3033
+ storageCache.clear()
3034
+ }
3035
+ })
3036
+ ```
3037
+
3038
+ If storage can change externally (another tab, server-set cookies), invalidate cache:
3039
+
3040
+ ### 7.6 Combine Multiple Array Iterations
3041
+
3042
+ **Impact: LOW-MEDIUM (reduces iterations)**
3043
+
3044
+ Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
3045
+
3046
+ **Incorrect: 3 iterations**
3047
+
3048
+ ```typescript
3049
+ const admins = users.filter(u => u.isAdmin)
3050
+ const testers = users.filter(u => u.isTester)
3051
+ const inactive = users.filter(u => !u.isActive)
3052
+ ```
3053
+
3054
+ **Correct: 1 iteration**
3055
+
3056
+ ```typescript
3057
+ const admins: User[] = []
3058
+ const testers: User[] = []
3059
+ const inactive: User[] = []
3060
+
3061
+ for (const user of users) {
3062
+ if (user.isAdmin) admins.push(user)
3063
+ if (user.isTester) testers.push(user)
3064
+ if (!user.isActive) inactive.push(user)
3065
+ }
3066
+ ```
3067
+
3068
+ ### 7.7 Defer Non-Critical Work with requestIdleCallback
3069
+
3070
+ **Impact: MEDIUM (keeps UI responsive during background tasks)**
3071
+
3072
+ Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
3073
+
3074
+ **Incorrect: blocks main thread during user interaction**
3075
+
3076
+ ```typescript
3077
+ function handleSearch(query: string) {
3078
+ const results = searchItems(query)
3079
+ setResults(results)
3080
+
3081
+ // These block the main thread immediately
3082
+ analytics.track('search', { query })
3083
+ saveToRecentSearches(query)
3084
+ prefetchTopResults(results.slice(0, 3))
3085
+ }
3086
+ ```
3087
+
3088
+ **Correct: defers non-critical work to idle time**
3089
+
3090
+ ```typescript
3091
+ function handleSearch(query: string) {
3092
+ const results = searchItems(query)
3093
+ setResults(results)
3094
+
3095
+ // Defer non-critical work to idle periods
3096
+ requestIdleCallback(() => {
3097
+ analytics.track('search', { query })
3098
+ })
3099
+
3100
+ requestIdleCallback(() => {
3101
+ saveToRecentSearches(query)
3102
+ })
3103
+
3104
+ requestIdleCallback(() => {
3105
+ prefetchTopResults(results.slice(0, 3))
3106
+ })
3107
+ }
3108
+ ```
3109
+
3110
+ **With timeout for required work:**
3111
+
3112
+ ```typescript
3113
+ // Ensure analytics fires within 2 seconds even if browser stays busy
3114
+ requestIdleCallback(
3115
+ () => analytics.track('page_view', { path: location.pathname }),
3116
+ { timeout: 2000 }
3117
+ )
3118
+ ```
3119
+
3120
+ **Chunking large tasks:**
3121
+
3122
+ ```typescript
3123
+ function processLargeDataset(items: Item[]) {
3124
+ let index = 0
3125
+
3126
+ function processChunk(deadline: IdleDeadline) {
3127
+ // Process items while we have idle time (aim for <50ms chunks)
3128
+ while (index < items.length && deadline.timeRemaining() > 0) {
3129
+ processItem(items[index])
3130
+ index++
3131
+ }
3132
+
3133
+ // Schedule next chunk if more items remain
3134
+ if (index < items.length) {
3135
+ requestIdleCallback(processChunk)
3136
+ }
3137
+ }
3138
+
3139
+ requestIdleCallback(processChunk)
3140
+ }
3141
+ ```
3142
+
3143
+ **With fallback for unsupported browsers:**
3144
+
3145
+ ```typescript
3146
+ const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))
3147
+
3148
+ scheduleIdleWork(() => {
3149
+ // Non-critical work
3150
+ })
3151
+ ```
3152
+
3153
+ **When to use:**
3154
+
3155
+ - Analytics and telemetry
3156
+
3157
+ - Saving state to localStorage/IndexedDB
3158
+
3159
+ - Prefetching resources for likely next actions
3160
+
3161
+ - Processing non-urgent data transformations
3162
+
3163
+ - Lazy initialization of non-critical features
3164
+
3165
+ **When NOT to use:**
3166
+
3167
+ - User-initiated actions that need immediate feedback
3168
+
3169
+ - Rendering updates the user is waiting for
3170
+
3171
+ - Time-sensitive operations
3172
+
3173
+ ### 7.8 Early Length Check for Array Comparisons
3174
+
3175
+ **Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**
3176
+
3177
+ When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
3178
+
3179
+ In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
3180
+
3181
+ **Incorrect: always runs expensive comparison**
3182
+
3183
+ ```typescript
3184
+ function hasChanges(current: string[], original: string[]) {
3185
+ // Always sorts and joins, even when lengths differ
3186
+ return current.sort().join() !== original.sort().join()
3187
+ }
3188
+ ```
3189
+
3190
+ 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.
3191
+
3192
+ **Correct (O(1) length check first):**
3193
+
3194
+ ```typescript
3195
+ function hasChanges(current: string[], original: string[]) {
3196
+ // Early return if lengths differ
3197
+ if (current.length !== original.length) {
3198
+ return true
3199
+ }
3200
+ // Only sort when lengths match
3201
+ const currentSorted = current.toSorted()
3202
+ const originalSorted = original.toSorted()
3203
+ for (let i = 0; i < currentSorted.length; i++) {
3204
+ if (currentSorted[i] !== originalSorted[i]) {
3205
+ return true
3206
+ }
3207
+ }
3208
+ return false
3209
+ }
3210
+ ```
3211
+
3212
+ This new approach is more efficient because:
3213
+
3214
+ - It avoids the overhead of sorting and joining the arrays when lengths differ
3215
+
3216
+ - It avoids consuming memory for the joined strings (especially important for large arrays)
3217
+
3218
+ - It avoids mutating the original arrays
3219
+
3220
+ - It returns early when a difference is found
3221
+
3222
+ ### 7.9 Early Return from Functions
3223
+
3224
+ **Impact: LOW-MEDIUM (avoids unnecessary computation)**
3225
+
3226
+ Return early when result is determined to skip unnecessary processing.
3227
+
3228
+ **Incorrect: processes all items even after finding answer**
3229
+
3230
+ ```typescript
3231
+ function validateUsers(users: User[]) {
3232
+ let hasError = false
3233
+ let errorMessage = ''
3234
+
3235
+ for (const user of users) {
3236
+ if (!user.email) {
3237
+ hasError = true
3238
+ errorMessage = 'Email required'
3239
+ }
3240
+ if (!user.name) {
3241
+ hasError = true
3242
+ errorMessage = 'Name required'
3243
+ }
3244
+ // Continues checking all users even after error found
3245
+ }
3246
+
3247
+ return hasError ? { valid: false, error: errorMessage } : { valid: true }
3248
+ }
3249
+ ```
3250
+
3251
+ **Correct: returns immediately on first error**
3252
+
3253
+ ```typescript
3254
+ function validateUsers(users: User[]) {
3255
+ for (const user of users) {
3256
+ if (!user.email) {
3257
+ return { valid: false, error: 'Email required' }
3258
+ }
3259
+ if (!user.name) {
3260
+ return { valid: false, error: 'Name required' }
3261
+ }
3262
+ }
3263
+
3264
+ return { valid: true }
3265
+ }
3266
+ ```
3267
+
3268
+ ### 7.10 Hoist RegExp Creation
3269
+
3270
+ **Impact: LOW-MEDIUM (avoids recreation)**
3271
+
3272
+ Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
3273
+
3274
+ **Incorrect: new RegExp every render**
3275
+
3276
+ ```tsx
3277
+ function Highlighter({ text, query }: Props) {
3278
+ const regex = new RegExp(`(${query})`, 'gi')
3279
+ const parts = text.split(regex)
3280
+ return <>{parts.map((part, i) => ...)}</>
3281
+ }
3282
+ ```
3283
+
3284
+ **Correct: memoize or hoist**
3285
+
3286
+ ```tsx
3287
+ const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
3288
+
3289
+ function Highlighter({ text, query }: Props) {
3290
+ const regex = useMemo(
3291
+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
3292
+ [query]
3293
+ )
3294
+ const parts = text.split(regex)
3295
+ return <>{parts.map((part, i) => ...)}</>
3296
+ }
3297
+ ```
3298
+
3299
+ **Warning: global regex has mutable state**
3300
+
3301
+ ```typescript
3302
+ const regex = /foo/g
3303
+ regex.test('foo') // true, lastIndex = 3
3304
+ regex.test('foo') // false, lastIndex = 0
3305
+ ```
3306
+
3307
+ Global regex (`/g`) has mutable `lastIndex` state:
3308
+
3309
+ ### 7.11 Use flatMap to Map and Filter in One Pass
3310
+
3311
+ **Impact: LOW-MEDIUM (eliminates intermediate array)**
3312
+
3313
+ Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
3314
+
3315
+ **Incorrect: 2 iterations, intermediate array**
3316
+
3317
+ ```typescript
3318
+ const userNames = users
3319
+ .map(user => user.isActive ? user.name : null)
3320
+ .filter(Boolean)
3321
+ ```
3322
+
3323
+ **Correct: 1 iteration, no intermediate array**
3324
+
3325
+ ```typescript
3326
+ const userNames = users.flatMap(user =>
3327
+ user.isActive ? [user.name] : []
3328
+ )
3329
+ ```
3330
+
3331
+ **More examples:**
3332
+
3333
+ ```typescript
3334
+ // Extract valid emails from responses
3335
+ // Before
3336
+ const emails = responses
3337
+ .map(r => r.success ? r.data.email : null)
3338
+ .filter(Boolean)
3339
+
3340
+ // After
3341
+ const emails = responses.flatMap(r =>
3342
+ r.success ? [r.data.email] : []
3343
+ )
3344
+
3345
+ // Parse and filter valid numbers
3346
+ // Before
3347
+ const numbers = strings
3348
+ .map(s => parseInt(s, 10))
3349
+ .filter(n => !isNaN(n))
3350
+
3351
+ // After
3352
+ const numbers = strings.flatMap(s => {
3353
+ const n = parseInt(s, 10)
3354
+ return isNaN(n) ? [] : [n]
3355
+ })
3356
+ ```
3357
+
3358
+ **When to use:**
3359
+
3360
+ - Transforming items while filtering some out
3361
+
3362
+ - Conditional mapping where some inputs produce no output
3363
+
3364
+ - Parsing/validating where invalid inputs should be skipped
3365
+
3366
+ ### 7.12 Use Loop for Min/Max Instead of Sort
3367
+
3368
+ **Impact: LOW (O(n) instead of O(n log n))**
3369
+
3370
+ Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
3371
+
3372
+ **Incorrect (O(n log n) - sort to find latest):**
3373
+
3374
+ ```typescript
3375
+ interface Project {
3376
+ id: string
3377
+ name: string
3378
+ updatedAt: number
3379
+ }
3380
+
3381
+ function getLatestProject(projects: Project[]) {
3382
+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
3383
+ return sorted[0]
3384
+ }
3385
+ ```
3386
+
3387
+ Sorts the entire array just to find the maximum value.
3388
+
3389
+ **Incorrect (O(n log n) - sort for oldest and newest):**
3390
+
3391
+ ```typescript
3392
+ function getOldestAndNewest(projects: Project[]) {
3393
+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)
3394
+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }
3395
+ }
3396
+ ```
3397
+
3398
+ Still sorts unnecessarily when only min/max are needed.
3399
+
3400
+ **Correct (O(n) - single loop):**
3401
+
3402
+ ```typescript
3403
+ function getLatestProject(projects: Project[]) {
3404
+ if (projects.length === 0) return null
3405
+
3406
+ let latest = projects[0]
3407
+
3408
+ for (let i = 1; i < projects.length; i++) {
3409
+ if (projects[i].updatedAt > latest.updatedAt) {
3410
+ latest = projects[i]
3411
+ }
3412
+ }
3413
+
3414
+ return latest
3415
+ }
3416
+
3417
+ function getOldestAndNewest(projects: Project[]) {
3418
+ if (projects.length === 0) return { oldest: null, newest: null }
3419
+
3420
+ let oldest = projects[0]
3421
+ let newest = projects[0]
3422
+
3423
+ for (let i = 1; i < projects.length; i++) {
3424
+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
3425
+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
3426
+ }
3427
+
3428
+ return { oldest, newest }
3429
+ }
3430
+ ```
3431
+
3432
+ Single pass through the array, no copying, no sorting.
3433
+
3434
+ **Alternative: Math.min/Math.max for small arrays**
3435
+
3436
+ ```typescript
3437
+ const numbers = [5, 2, 8, 1, 9]
3438
+ const min = Math.min(...numbers)
3439
+ const max = Math.max(...numbers)
3440
+ ```
3441
+
3442
+ 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.
3443
+
3444
+ ### 7.13 Use Set/Map for O(1) Lookups
3445
+
3446
+ **Impact: LOW-MEDIUM (O(n) to O(1))**
3447
+
3448
+ Convert arrays to Set/Map for repeated membership checks.
3449
+
3450
+ **Incorrect (O(n) per check):**
3451
+
3452
+ ```typescript
3453
+ const allowedIds = ['a', 'b', 'c', ...]
3454
+ items.filter(item => allowedIds.includes(item.id))
3455
+ ```
3456
+
3457
+ **Correct (O(1) per check):**
3458
+
3459
+ ```typescript
3460
+ const allowedIds = new Set(['a', 'b', 'c', ...])
3461
+ items.filter(item => allowedIds.has(item.id))
3462
+ ```
3463
+
3464
+ ### 7.14 Use toSorted() Instead of sort() for Immutability
3465
+
3466
+ **Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**
3467
+
3468
+ `.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.
3469
+
3470
+ **Incorrect: mutates original array**
3471
+
3472
+ ```typescript
3473
+ function UserList({ users }: { users: User[] }) {
3474
+ // Mutates the users prop array!
3475
+ const sorted = useMemo(
3476
+ () => users.sort((a, b) => a.name.localeCompare(b.name)),
3477
+ [users]
3478
+ )
3479
+ return <div>{sorted.map(renderUser)}</div>
3480
+ }
3481
+ ```
3482
+
3483
+ **Correct: creates new array**
3484
+
3485
+ ```typescript
3486
+ function UserList({ users }: { users: User[] }) {
3487
+ // Creates new sorted array, original unchanged
3488
+ const sorted = useMemo(
3489
+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
3490
+ [users]
3491
+ )
3492
+ return <div>{sorted.map(renderUser)}</div>
3493
+ }
3494
+ ```
3495
+
3496
+ **Why this matters in React:**
3497
+
3498
+ 1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
3499
+
3500
+ 2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
3501
+
3502
+ **Browser support: fallback for older browsers**
3503
+
3504
+ ```typescript
3505
+ // Fallback for older browsers
3506
+ const sorted = [...items].sort((a, b) => a.value - b.value)
3507
+ ```
3508
+
3509
+ `.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
3510
+
3511
+ **Other immutable array methods:**
3512
+
3513
+ - `.toSorted()` - immutable sort
3514
+
3515
+ - `.toReversed()` - immutable reverse
3516
+
3517
+ - `.toSpliced()` - immutable splice
3518
+
3519
+ - `.with()` - immutable element replacement
3520
+
3521
+ ---
3522
+
3523
+ ## 8. Advanced Patterns
3524
+
3525
+ **Impact: LOW**
3526
+
3527
+ Advanced patterns for specific cases that require careful implementation.
3528
+
3529
+ ### 8.1 Initialize App Once, Not Per Mount
3530
+
3531
+ **Impact: LOW-MEDIUM (avoids duplicate init in development)**
3532
+
3533
+ 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.
3534
+
3535
+ **Incorrect: runs twice in dev, re-runs on remount**
3536
+
3537
+ ```tsx
3538
+ function Comp() {
3539
+ useEffect(() => {
3540
+ loadFromStorage()
3541
+ checkAuthToken()
3542
+ }, [])
3543
+
3544
+ // ...
3545
+ }
3546
+ ```
3547
+
3548
+ **Correct: once per app load**
3549
+
3550
+ ```tsx
3551
+ let didInit = false
3552
+
3553
+ function Comp() {
3554
+ useEffect(() => {
3555
+ if (didInit) return
3556
+ didInit = true
3557
+ loadFromStorage()
3558
+ checkAuthToken()
3559
+ }, [])
3560
+
3561
+ // ...
3562
+ }
3563
+ ```
3564
+
3565
+ Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
3566
+
3567
+ ### 8.2 Store Event Handlers in Refs
3568
+
3569
+ **Impact: LOW (stable subscriptions)**
3570
+
3571
+ Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
3572
+
3573
+ **Incorrect: re-subscribes on every render**
3574
+
3575
+ ```tsx
3576
+ function useWindowEvent(event: string, handler: (e) => void) {
3577
+ useEffect(() => {
3578
+ window.addEventListener(event, handler)
3579
+ return () => window.removeEventListener(event, handler)
3580
+ }, [event, handler])
3581
+ }
3582
+ ```
3583
+
3584
+ **Correct: stable subscription**
3585
+
3586
+ ```tsx
3587
+ import { useEffectEvent } from 'react'
3588
+
3589
+ function useWindowEvent(event: string, handler: (e) => void) {
3590
+ const onEvent = useEffectEvent(handler)
3591
+
3592
+ useEffect(() => {
3593
+ window.addEventListener(event, onEvent)
3594
+ return () => window.removeEventListener(event, onEvent)
3595
+ }, [event])
3596
+ }
3597
+ ```
3598
+
3599
+ **Alternative: use `useEffectEvent` if you're on latest React:**
3600
+
3601
+ `useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
3602
+
3603
+ ### 8.3 useEffectEvent for Stable Callback Refs
3604
+
3605
+ **Impact: LOW (prevents effect re-runs)**
3606
+
3607
+ Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
3608
+
3609
+ **Incorrect: effect re-runs on every callback change**
3610
+
3611
+ ```tsx
3612
+ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
3613
+ const [query, setQuery] = useState('')
3614
+
3615
+ useEffect(() => {
3616
+ const timeout = setTimeout(() => onSearch(query), 300)
3617
+ return () => clearTimeout(timeout)
3618
+ }, [query, onSearch])
3619
+ }
3620
+ ```
3621
+
3622
+ **Correct: using React's useEffectEvent**
3623
+
3624
+ ```tsx
3625
+ import { useEffectEvent } from 'react';
3626
+
3627
+ function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
3628
+ const [query, setQuery] = useState('')
3629
+ const onSearchEvent = useEffectEvent(onSearch)
3630
+
3631
+ useEffect(() => {
3632
+ const timeout = setTimeout(() => onSearchEvent(query), 300)
3633
+ return () => clearTimeout(timeout)
3634
+ }, [query])
3635
+ }
3636
+ ```
3637
+
3638
+ ---
3639
+
3640
+ ## References
3641
+
3642
+ 1. [https://react.dev](https://react.dev)
3643
+ 2. [https://nextjs.org](https://nextjs.org)
3644
+ 3. [https://swr.vercel.app](https://swr.vercel.app)
3645
+ 4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
3646
+ 5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
3647
+ 6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
3648
+ 7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)