@lobehub/lobehub 2.0.0-next.338 → 2.0.0-next.339

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