@runweave/server-linux-x64 0.1.8 → 0.1.10

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