@ruyfranca/myskills 1.0.35 → 1.0.36
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.
- package/.agent/skills/analyze-project/SKILL.md +1 -2
- package/.agent/skills/antigravity-design-expert/SKILL.md +1 -2
- package/.agent/skills/api-integration-specialist/SKILL.md +5 -2
- package/.agent/skills/api-patterns/SKILL.md +5 -2
- package/.agent/skills/app-builder/SKILL.md +5 -2
- package/.agent/skills/artifacts-builder/SKILL.md +4 -1
- package/.agent/skills/bash-linux/SKILL.md +4 -1
- package/.agent/skills/behavioral-modes/SKILL.md +5 -2
- package/.agent/skills/brainstorming/SKILL.md +5 -2
- package/.agent/skills/business-analyst/SKILL.md +4 -1
- package/.agent/skills/canvas-design/SKILL.md +5 -2
- package/.agent/skills/clean-code/SKILL.md +5 -2
- package/.agent/skills/code-review-checklist/SKILL.md +5 -2
- package/.agent/skills/code-reviewer/SKILL.md +5 -2
- package/.agent/skills/content-research-writer/SKILL.md +5 -2
- package/.agent/skills/copywriting/SKILL.md +5 -2
- package/.agent/skills/cqrs-implementation/SKILL.md +2 -2
- package/.agent/skills/creative-design-figma/SKILL.md +5 -2
- package/.agent/skills/cto-advisor/SKILL.md +5 -2
- package/.agent/skills/database-design/SKILL.md +5 -2
- package/.agent/skills/ddd-strategic-design/SKILL.md +2 -2
- package/.agent/skills/ddd-tactical-patterns/SKILL.md +2 -2
- package/.agent/skills/deployment-procedures/SKILL.md +5 -2
- package/.agent/skills/doc-coauthoring/SKILL.md +2 -3
- package/.agent/skills/docker-expert/SKILL.md +5 -2
- package/.agent/skills/documentation-templates/SKILL.md +5 -2
- package/.agent/skills/elixir-pro/SKILL.md +2 -2
- package/.agent/skills/email-composer/SKILL.md +5 -2
- package/.agent/skills/event-sourcing-architect/SKILL.md +2 -2
- package/.agent/skills/figma-dev-mode/SKILL.md +5 -2
- package/.agent/skills/file-organizer/SKILL.md +5 -2
- package/.agent/skills/frontend-design/SKILL.md +5 -2
- package/.agent/skills/game-development/SKILL.md +5 -2
- package/.agent/skills/geo-fundamentals/SKILL.md +5 -2
- package/.agent/skills/golang-pro/SKILL.md +2 -2
- package/.agent/skills/i18n-localization/SKILL.md +5 -2
- package/.agent/skills/intelligent-routing/SKILL.md +5 -2
- package/.agent/skills/invoice-organizer/SKILL.md +5 -2
- package/.agent/skills/kotlin-coroutines-expert/SKILL.md +2 -2
- package/.agent/skills/lead-research-assistant/SKILL.md +5 -2
- package/.agent/skills/leiloeiro-risco/SKILL.md +2 -3
- package/.agent/skills/lint-and-validate/SKILL.md +5 -2
- package/.agent/skills/marketing-campaigns/SKILL.md +5 -2
- package/.agent/skills/mcp-builder/SKILL.md +5 -2
- package/.agent/skills/mobile-design/SKILL.md +5 -2
- package/.agent/skills/modern-javascript-patterns/SKILL.md +1 -1
- package/.agent/skills/monorepo-architect/SKILL.md +2 -2
- package/.agent/skills/nestjs/SKILL.md +5 -2
- package/.agent/skills/nextjs-best-practices/SKILL.md +5 -2
- package/.agent/skills/nextjs-react-expert/SKILL.md +1 -1
- package/.agent/skills/parallel-agents/SKILL.md +5 -2
- package/.agent/skills/pdf-processing-pro/SKILL.md +5 -2
- package/.agent/skills/performance-profiling/SKILL.md +5 -2
- package/.agent/skills/powershell-windows/SKILL.md +5 -2
- package/.agent/skills/pptx/SKILL.md +5 -2
- package/.agent/skills/product-manager/SKILL.md +5 -2
- package/.agent/skills/python-patterns/SKILL.md +5 -2
- package/.agent/skills/react-best-practices/SKILL.md +208 -0
- package/.agent/skills/react-best-practices/references/react-performance-guidelines.md +1865 -0
- package/.agent/skills/react-best-practices/references/rules/_sections.md +46 -0
- package/.agent/skills/react-best-practices/references/rules/_template.md +28 -0
- package/.agent/skills/react-best-practices/references/rules/advanced-event-handler-refs.md +38 -0
- package/.agent/skills/react-best-practices/references/rules/advanced-use-latest.md +49 -0
- package/.agent/skills/react-best-practices/references/rules/async-api-routes.md +38 -0
- package/.agent/skills/react-best-practices/references/rules/async-defer-await.md +80 -0
- package/.agent/skills/react-best-practices/references/rules/async-dependencies.md +36 -0
- package/.agent/skills/react-best-practices/references/rules/async-parallel.md +28 -0
- package/.agent/skills/react-best-practices/references/rules/async-suspense-boundaries.md +66 -0
- package/.agent/skills/react-best-practices/references/rules/bundle-barrel-imports.md +59 -0
- package/.agent/skills/react-best-practices/references/rules/bundle-conditional.md +31 -0
- package/.agent/skills/react-best-practices/references/rules/bundle-defer-third-party.md +49 -0
- package/.agent/skills/react-best-practices/references/rules/bundle-dynamic-imports.md +35 -0
- package/.agent/skills/react-best-practices/references/rules/bundle-preload.md +50 -0
- package/.agent/skills/react-best-practices/references/rules/client-event-listeners.md +74 -0
- package/.agent/skills/react-best-practices/references/rules/client-swr-dedup.md +56 -0
- package/.agent/skills/react-best-practices/references/rules/download_rules.sh +63 -0
- package/.agent/skills/react-best-practices/references/rules/js-batch-dom-css.md +82 -0
- package/.agent/skills/react-best-practices/references/rules/js-cache-function-results.md +80 -0
- package/.agent/skills/react-best-practices/references/rules/js-cache-property-access.md +28 -0
- package/.agent/skills/react-best-practices/references/rules/js-cache-storage.md +68 -0
- package/.agent/skills/react-best-practices/references/rules/js-combine-iterations.md +32 -0
- package/.agent/skills/react-best-practices/references/rules/js-early-exit.md +50 -0
- package/.agent/skills/react-best-practices/references/rules/js-hoist-regexp.md +43 -0
- package/.agent/skills/react-best-practices/references/rules/js-index-maps.md +37 -0
- package/.agent/skills/react-best-practices/references/rules/js-length-check-first.md +49 -0
- package/.agent/skills/react-best-practices/references/rules/js-min-max-loop.md +82 -0
- package/.agent/skills/react-best-practices/references/rules/js-set-map-lookups.md +24 -0
- package/.agent/skills/react-best-practices/references/rules/js-tosorted-immutable.md +57 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-activity.md +26 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-animate-svg-wrapper.md +47 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-conditional-render.md +40 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-content-visibility.md +38 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-hoist-jsx.md +44 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-hydration-no-flicker.md +82 -0
- package/.agent/skills/react-best-practices/references/rules/rendering-svg-precision.md +28 -0
- package/.agent/skills/react-best-practices/references/rules/rerender-defer-reads.md +39 -0
- package/.agent/skills/react-best-practices/references/rules/rerender-dependencies.md +45 -0
- package/.agent/skills/react-best-practices/references/rules/rerender-derived-state.md +29 -0
- package/.agent/skills/react-best-practices/references/rules/rerender-lazy-state-init.md +58 -0
- package/.agent/skills/react-best-practices/references/rules/rerender-memo.md +42 -0
- package/.agent/skills/react-best-practices/references/rules/rerender-transitions.md +40 -0
- package/.agent/skills/react-best-practices/references/rules/server-cache-lru.md +37 -0
- package/.agent/skills/react-best-practices/references/rules/server-cache-react.md +26 -0
- package/.agent/skills/react-best-practices/references/rules/server-parallel-fetching.md +79 -0
- package/.agent/skills/react-best-practices/references/rules/server-serialization.md +38 -0
- package/.agent/skills/react-patterns/SKILL.md +2 -2
- package/.agent/skills/react-state-management/SKILL.md +2 -2
- package/.agent/skills/red-team-tactics/SKILL.md +5 -2
- package/.agent/skills/ruby-pro/SKILL.md +2 -2
- package/.agent/skills/rust-pro/SKILL.md +5 -1
- package/.agent/skills/sdd-spec-writer/SKILL.md +5 -2
- package/.agent/skills/security/SKILL.md +4 -1
- package/.agent/skills/senior-devops/SKILL.md +4 -1
- package/.agent/skills/senior-frontend/SKILL.md +5 -2
- package/.agent/skills/senior-fullstack/SKILL.md +5 -2
- package/.agent/skills/senior-prompt-engineer/SKILL.md +5 -2
- package/.agent/skills/senior-qa/SKILL.md +5 -2
- package/.agent/skills/senior-security/SKILL.md +5 -2
- package/.agent/skills/seo-optimizer/SKILL.md +5 -2
- package/.agent/skills/server-management/SKILL.md +5 -2
- package/.agent/skills/skill-developer/SKILL.md +1 -2
- package/.agent/skills/software-architecture/SKILL.md +5 -2
- package/.agent/skills/supabase-postgres/SKILL.md +5 -2
- package/.agent/skills/systematic-debugging/SKILL.md +5 -2
- package/.agent/skills/tailwind-patterns/SKILL.md +5 -2
- package/.agent/skills/tdd-workflow/SKILL.md +5 -2
- package/.agent/skills/test-driven-development/SKILL.md +5 -2
- package/.agent/skills/testing-patterns/SKILL.md +5 -2
- package/.agent/skills/theme-factory/SKILL.md +5 -2
- package/.agent/skills/ui-design-system/SKILL.md +5 -2
- package/.agent/skills/ui-ux-pro-max/SKILL.md +5 -2
- package/.agent/skills/uncle-bob-craft/SKILL.md +2 -3
- package/.agent/skills/ux-researcher-designer/SKILL.md +5 -2
- package/.agent/skills/vulnerability-scanner/SKILL.md +5 -2
- package/.agent/skills/web-design-guidelines/SKILL.md +5 -2
- package/.agent/skills/web-performance/SKILL.md +5 -2
- package/.agent/skills/webapp-testing/SKILL.md +5 -2
- package/.agent/skills/writing-plans/SKILL.md +5 -2
- package/.agent/skills/xlsx/SKILL.md +5 -2
- package/.agent/skills/zod-validation-expert/SKILL.md +2 -2
- package/README.md +3 -2
- package/package.json +1 -1
|
@@ -0,0 +1,1865 @@
|
|
|
1
|
+
# React Best Practices - Complete Document
|
|
2
|
+
|
|
3
|
+
**Version 0.1.0**
|
|
4
|
+
Vercel Engineering
|
|
5
|
+
January 2026
|
|
6
|
+
|
|
7
|
+
> **Note:**
|
|
8
|
+
> This document is mainly for agents and LLMs to follow when maintaining, generating, or refactoring React and Next.js codebases at Vercel.
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
## Abstract
|
|
13
|
+
|
|
14
|
+
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.
|
|
15
|
+
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
## Table of Contents
|
|
19
|
+
|
|
20
|
+
1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**
|
|
21
|
+
- 1.1 [Defer Await Until Needed](#11)
|
|
22
|
+
- 1.2 [Dependency-Based Parallelization](#12)
|
|
23
|
+
- 1.3 [Prevent Waterfall Chains in API Routes](#13)
|
|
24
|
+
- 1.4 [Promise.all() for Independent Operations](#14)
|
|
25
|
+
- 1.5 [Strategic Suspense Boundaries](#15)
|
|
26
|
+
2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**
|
|
27
|
+
- 2.1 [Avoid Barrel File Imports](#21)
|
|
28
|
+
- 2.2 [Conditional Module Loading](#22)
|
|
29
|
+
- 2.3 [Defer Non-Critical Third-Party Libraries](#23)
|
|
30
|
+
- 2.4 [Dynamic Imports for Heavy Components](#24)
|
|
31
|
+
- 2.5 [Preload Based on User Intent](#25)
|
|
32
|
+
3. [Server-Side Performance](#3-server-side-performance) — **HIGH**
|
|
33
|
+
- 3.1 [Cross-Request LRU Caching](#31)
|
|
34
|
+
- 3.2 [Minimize Serialization at RSC Boundaries](#32)
|
|
35
|
+
- 3.3 [Parallel Data Fetching with Component Composition](#33)
|
|
36
|
+
- 3.4 [Per-Request Deduplication with React.cache()](#34)
|
|
37
|
+
4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**
|
|
38
|
+
- 4.1 [Deduplicate Global Event Listeners](#41)
|
|
39
|
+
- 4.2 [Use SWR for Automatic Deduplication](#42)
|
|
40
|
+
5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**
|
|
41
|
+
- 5.1 [Defer State Reads to Usage Point](#51)
|
|
42
|
+
- 5.2 [Extract to Memoized Components](#52)
|
|
43
|
+
- 5.3 [Narrow Effect Dependencies](#53)
|
|
44
|
+
- 5.4 [Subscribe to Derived State](#54)
|
|
45
|
+
- 5.5 [Use Lazy State Initialization](#55)
|
|
46
|
+
- 5.6 [Use Transitions for Non-Urgent Updates](#56)
|
|
47
|
+
6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**
|
|
48
|
+
- 6.1 [Animate SVG Wrapper Instead of SVG Element](#61)
|
|
49
|
+
- 6.2 [CSS content-visibility for Long Lists](#62)
|
|
50
|
+
- 6.3 [Hoist Static JSX Elements](#63)
|
|
51
|
+
- 6.4 [Optimize SVG Precision](#64)
|
|
52
|
+
- 6.5 [Prevent Hydration Mismatch Without Flickering](#65)
|
|
53
|
+
- 6.6 [Use Activity Component for Show/Hide](#66)
|
|
54
|
+
- 6.7 [Use Explicit Conditional Rendering](#67)
|
|
55
|
+
7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**
|
|
56
|
+
- 7.1 [Batch DOM CSS Changes](#71)
|
|
57
|
+
- 7.2 [Build Index Maps for Repeated Lookups](#72)
|
|
58
|
+
- 7.3 [Cache Property Access in Loops](#73)
|
|
59
|
+
- 7.4 [Cache Repeated Function Calls](#74)
|
|
60
|
+
- 7.5 [Cache Storage API Calls](#75)
|
|
61
|
+
- 7.6 [Combine Multiple Array Iterations](#76)
|
|
62
|
+
- 7.7 [Early Length Check for Array Comparisons](#77)
|
|
63
|
+
- 7.8 [Early Return from Functions](#78)
|
|
64
|
+
- 7.9 [Hoist RegExp Creation](#79)
|
|
65
|
+
- 7.10 [Use Loop for Min/Max Instead of Sort](#710)
|
|
66
|
+
- 7.11 [Use Set/Map for O(1) Lookups](#711)
|
|
67
|
+
- 7.12 [Use toSorted() Instead of sort() for Immutability](#712)
|
|
68
|
+
8. [Advanced Patterns](#8-advanced-patterns) — **LOW**
|
|
69
|
+
- 8.1 [Store Event Handlers in Refs](#81)
|
|
70
|
+
- 8.2 [useLatest for Stable Callback Refs](#82)
|
|
71
|
+
|
|
72
|
+
---
|
|
73
|
+
|
|
74
|
+
## 1. Eliminating Waterfalls
|
|
75
|
+
|
|
76
|
+
**Impact: CRITICAL**
|
|
77
|
+
|
|
78
|
+
Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
|
|
79
|
+
|
|
80
|
+
### 1.1 Defer Await Until Needed
|
|
81
|
+
|
|
82
|
+
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
|
83
|
+
|
|
84
|
+
**Incorrect: blocks both branches**
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
async function handleRequest(userId: string, skipProcessing: boolean) {
|
|
88
|
+
const userData = await fetchUserData(userId)
|
|
89
|
+
|
|
90
|
+
if (skipProcessing) {
|
|
91
|
+
// Returns immediately but still waited for userData
|
|
92
|
+
return { skipped: true }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Only this branch uses userData
|
|
96
|
+
return processUserData(userData)
|
|
97
|
+
}
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
**Correct: only blocks when needed**
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
async function handleRequest(userId: string, skipProcessing: boolean) {
|
|
104
|
+
if (skipProcessing) {
|
|
105
|
+
// Returns immediately without waiting
|
|
106
|
+
return { skipped: true }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Fetch only when needed
|
|
110
|
+
const userData = await fetchUserData(userId)
|
|
111
|
+
return processUserData(userData)
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
**Another example: early return optimization**
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
// Incorrect: always fetches permissions
|
|
119
|
+
async function updateResource(resourceId: string, userId: string) {
|
|
120
|
+
const permissions = await fetchPermissions(userId)
|
|
121
|
+
const resource = await getResource(resourceId)
|
|
122
|
+
|
|
123
|
+
if (!resource) {
|
|
124
|
+
return { error: 'Not found' }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (!permissions.canEdit) {
|
|
128
|
+
return { error: 'Forbidden' }
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return await updateResourceData(resource, permissions)
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Correct: fetches only when needed
|
|
135
|
+
async function updateResource(resourceId: string, userId: string) {
|
|
136
|
+
const resource = await getResource(resourceId)
|
|
137
|
+
|
|
138
|
+
if (!resource) {
|
|
139
|
+
return { error: 'Not found' }
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const permissions = await fetchPermissions(userId)
|
|
143
|
+
|
|
144
|
+
if (!permissions.canEdit) {
|
|
145
|
+
return { error: 'Forbidden' }
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
return await updateResourceData(resource, permissions)
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
|
153
|
+
|
|
154
|
+
### 1.2 Dependency-Based Parallelization
|
|
155
|
+
|
|
156
|
+
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
|
157
|
+
|
|
158
|
+
**Incorrect: profile waits for config unnecessarily**
|
|
159
|
+
|
|
160
|
+
```typescript
|
|
161
|
+
const [user, config] = await Promise.all([
|
|
162
|
+
fetchUser(),
|
|
163
|
+
fetchConfig()
|
|
164
|
+
])
|
|
165
|
+
const profile = await fetchProfile(user.id)
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
**Correct: config and profile run in parallel**
|
|
169
|
+
|
|
170
|
+
```typescript
|
|
171
|
+
import { all } from 'better-all'
|
|
172
|
+
|
|
173
|
+
const { user, config, profile } = await all({
|
|
174
|
+
async user() { return fetchUser() },
|
|
175
|
+
async config() { return fetchConfig() },
|
|
176
|
+
async profile() {
|
|
177
|
+
return fetchProfile((await this.$.user).id)
|
|
178
|
+
}
|
|
179
|
+
})
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
|
183
|
+
|
|
184
|
+
### 1.3 Prevent Waterfall Chains in API Routes
|
|
185
|
+
|
|
186
|
+
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
|
187
|
+
|
|
188
|
+
**Incorrect: config waits for auth, data waits for both**
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
export async function GET(request: Request) {
|
|
192
|
+
const session = await auth()
|
|
193
|
+
const config = await fetchConfig()
|
|
194
|
+
const data = await fetchData(session.user.id)
|
|
195
|
+
return Response.json({ data, config })
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**Correct: auth and config start immediately**
|
|
200
|
+
|
|
201
|
+
```typescript
|
|
202
|
+
export async function GET(request: Request) {
|
|
203
|
+
const sessionPromise = auth()
|
|
204
|
+
const configPromise = fetchConfig()
|
|
205
|
+
const session = await sessionPromise
|
|
206
|
+
const [config, data] = await Promise.all([
|
|
207
|
+
configPromise,
|
|
208
|
+
fetchData(session.user.id)
|
|
209
|
+
])
|
|
210
|
+
return Response.json({ data, config })
|
|
211
|
+
}
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
|
215
|
+
|
|
216
|
+
### 1.4 Promise.all() for Independent Operations
|
|
217
|
+
|
|
218
|
+
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
|
219
|
+
|
|
220
|
+
**Incorrect: sequential execution, 3 round trips**
|
|
221
|
+
|
|
222
|
+
```typescript
|
|
223
|
+
const user = await fetchUser()
|
|
224
|
+
const posts = await fetchPosts()
|
|
225
|
+
const comments = await fetchComments()
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
**Correct: parallel execution, 1 round trip**
|
|
229
|
+
|
|
230
|
+
```typescript
|
|
231
|
+
const [user, posts, comments] = await Promise.all([
|
|
232
|
+
fetchUser(),
|
|
233
|
+
fetchPosts(),
|
|
234
|
+
fetchComments()
|
|
235
|
+
])
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
### 1.5 Strategic Suspense Boundaries
|
|
239
|
+
|
|
240
|
+
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
|
241
|
+
|
|
242
|
+
**Incorrect: wrapper blocked by data fetching**
|
|
243
|
+
|
|
244
|
+
```tsx
|
|
245
|
+
async function Page() {
|
|
246
|
+
const data = await fetchData() // Blocks entire page
|
|
247
|
+
|
|
248
|
+
return (
|
|
249
|
+
<div>
|
|
250
|
+
<div>Sidebar</div>
|
|
251
|
+
<div>Header</div>
|
|
252
|
+
<div>
|
|
253
|
+
<DataDisplay data={data} />
|
|
254
|
+
</div>
|
|
255
|
+
<div>Footer</div>
|
|
256
|
+
</div>
|
|
257
|
+
)
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
The entire layout waits for data even though only the middle section needs it.
|
|
262
|
+
|
|
263
|
+
**Correct: wrapper shows immediately, data streams in**
|
|
264
|
+
|
|
265
|
+
```tsx
|
|
266
|
+
function Page() {
|
|
267
|
+
return (
|
|
268
|
+
<div>
|
|
269
|
+
<div>Sidebar</div>
|
|
270
|
+
<div>Header</div>
|
|
271
|
+
<div>
|
|
272
|
+
<Suspense fallback={<Skeleton />}>
|
|
273
|
+
<DataDisplay />
|
|
274
|
+
</Suspense>
|
|
275
|
+
</div>
|
|
276
|
+
<div>Footer</div>
|
|
277
|
+
</div>
|
|
278
|
+
)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function DataDisplay() {
|
|
282
|
+
const data = await fetchData() // Only blocks this component
|
|
283
|
+
return <div>{data.content}</div>
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
|
288
|
+
|
|
289
|
+
---
|
|
290
|
+
|
|
291
|
+
## 2. Bundle Size Optimization
|
|
292
|
+
|
|
293
|
+
**Impact: CRITICAL**
|
|
294
|
+
|
|
295
|
+
Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
|
|
296
|
+
|
|
297
|
+
### 2.1 Avoid Barrel File Imports
|
|
298
|
+
|
|
299
|
+
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'`).
|
|
300
|
+
|
|
301
|
+
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.
|
|
302
|
+
|
|
303
|
+
**Incorrect: imports entire library**
|
|
304
|
+
|
|
305
|
+
```tsx
|
|
306
|
+
import { Check, X, Menu } from 'lucide-react'
|
|
307
|
+
// Loads 1,583 modules, takes ~2.8s extra in dev
|
|
308
|
+
// Runtime cost: 200-800ms on every cold start
|
|
309
|
+
|
|
310
|
+
import { Button, TextField } from '@mui/material'
|
|
311
|
+
// Loads 2,225 modules, takes ~4.2s extra in dev
|
|
312
|
+
```
|
|
313
|
+
|
|
314
|
+
**Correct: imports only what you need**
|
|
315
|
+
|
|
316
|
+
```tsx
|
|
317
|
+
import Check from 'lucide-react/dist/esm/icons/check'
|
|
318
|
+
import X from 'lucide-react/dist/esm/icons/x'
|
|
319
|
+
import Menu from 'lucide-react/dist/esm/icons/menu'
|
|
320
|
+
// Loads only 3 modules (~2KB vs ~1MB)
|
|
321
|
+
|
|
322
|
+
import Button from '@mui/material/Button'
|
|
323
|
+
import TextField from '@mui/material/TextField'
|
|
324
|
+
// Loads only what you use
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
**Alternative: Next.js 13.5+**
|
|
328
|
+
|
|
329
|
+
```js
|
|
330
|
+
// next.config.js - use optimizePackageImports
|
|
331
|
+
module.exports = {
|
|
332
|
+
experimental: {
|
|
333
|
+
optimizePackageImports: ['lucide-react', '@mui/material']
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Then you can keep the ergonomic barrel imports:
|
|
338
|
+
import { Check, X, Menu } from 'lucide-react'
|
|
339
|
+
// Automatically transformed to direct imports at build time
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
|
|
343
|
+
|
|
344
|
+
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`.
|
|
345
|
+
|
|
346
|
+
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)
|
|
347
|
+
|
|
348
|
+
### 2.2 Conditional Module Loading
|
|
349
|
+
|
|
350
|
+
Load large data or modules only when a feature is activated.
|
|
351
|
+
|
|
352
|
+
**Example: lazy-load animation frames**
|
|
353
|
+
|
|
354
|
+
```tsx
|
|
355
|
+
function AnimationPlayer({ enabled }: { enabled: boolean }) {
|
|
356
|
+
const [frames, setFrames] = useState<Frame[] | null>(null)
|
|
357
|
+
|
|
358
|
+
useEffect(() => {
|
|
359
|
+
if (enabled && !frames && typeof window !== 'undefined') {
|
|
360
|
+
import('./animation-frames.js')
|
|
361
|
+
.then(mod => setFrames(mod.frames))
|
|
362
|
+
.catch(() => setEnabled(false))
|
|
363
|
+
}
|
|
364
|
+
}, [enabled, frames])
|
|
365
|
+
|
|
366
|
+
if (!frames) return <Skeleton />
|
|
367
|
+
return <Canvas frames={frames} />
|
|
368
|
+
}
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
|
|
372
|
+
|
|
373
|
+
### 2.3 Defer Non-Critical Third-Party Libraries
|
|
374
|
+
|
|
375
|
+
Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
|
|
376
|
+
|
|
377
|
+
**Incorrect: blocks initial bundle**
|
|
378
|
+
|
|
379
|
+
```tsx
|
|
380
|
+
import { Analytics } from '@vercel/analytics/react'
|
|
381
|
+
|
|
382
|
+
export default function RootLayout({ children }) {
|
|
383
|
+
return (
|
|
384
|
+
<html>
|
|
385
|
+
<body>
|
|
386
|
+
{children}
|
|
387
|
+
<Analytics />
|
|
388
|
+
</body>
|
|
389
|
+
</html>
|
|
390
|
+
)
|
|
391
|
+
}
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
**Correct: loads after hydration**
|
|
395
|
+
|
|
396
|
+
```tsx
|
|
397
|
+
import dynamic from 'next/dynamic'
|
|
398
|
+
|
|
399
|
+
const Analytics = dynamic(
|
|
400
|
+
() => import('@vercel/analytics/react').then(m => m.Analytics),
|
|
401
|
+
{ ssr: false }
|
|
402
|
+
)
|
|
403
|
+
|
|
404
|
+
export default function RootLayout({ children }) {
|
|
405
|
+
return (
|
|
406
|
+
<html>
|
|
407
|
+
<body>
|
|
408
|
+
{children}
|
|
409
|
+
<Analytics />
|
|
410
|
+
</body>
|
|
411
|
+
</html>
|
|
412
|
+
)
|
|
413
|
+
}
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
### 2.4 Dynamic Imports for Heavy Components
|
|
417
|
+
|
|
418
|
+
Use `next/dynamic` to lazy-load large components not needed on initial render.
|
|
419
|
+
|
|
420
|
+
**Incorrect: Monaco bundles with main chunk ~300KB**
|
|
421
|
+
|
|
422
|
+
```tsx
|
|
423
|
+
import { MonacoEditor } from './monaco-editor'
|
|
424
|
+
|
|
425
|
+
function CodePanel({ code }: { code: string }) {
|
|
426
|
+
return <MonacoEditor value={code} />
|
|
427
|
+
}
|
|
428
|
+
```
|
|
429
|
+
|
|
430
|
+
**Correct: Monaco loads on demand**
|
|
431
|
+
|
|
432
|
+
```tsx
|
|
433
|
+
import dynamic from 'next/dynamic'
|
|
434
|
+
|
|
435
|
+
const MonacoEditor = dynamic(
|
|
436
|
+
() => import('./monaco-editor').then(m => m.MonacoEditor),
|
|
437
|
+
{ ssr: false }
|
|
438
|
+
)
|
|
439
|
+
|
|
440
|
+
function CodePanel({ code }: { code: string }) {
|
|
441
|
+
return <MonacoEditor value={code} />
|
|
442
|
+
}
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
### 2.5 Preload Based on User Intent
|
|
446
|
+
|
|
447
|
+
Preload heavy bundles before they're needed to reduce perceived latency.
|
|
448
|
+
|
|
449
|
+
**Example: preload on hover/focus**
|
|
450
|
+
|
|
451
|
+
```tsx
|
|
452
|
+
function EditorButton({ onClick }: { onClick: () => void }) {
|
|
453
|
+
const preload = () => {
|
|
454
|
+
if (typeof window !== 'undefined') {
|
|
455
|
+
void import('./monaco-editor')
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
return (
|
|
460
|
+
<button
|
|
461
|
+
onMouseEnter={preload}
|
|
462
|
+
onFocus={preload}
|
|
463
|
+
onClick={onClick}
|
|
464
|
+
>
|
|
465
|
+
Open Editor
|
|
466
|
+
</button>
|
|
467
|
+
)
|
|
468
|
+
}
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
**Example: preload when feature flag is enabled**
|
|
472
|
+
|
|
473
|
+
```tsx
|
|
474
|
+
function FlagsProvider({ children, flags }: Props) {
|
|
475
|
+
useEffect(() => {
|
|
476
|
+
if (flags.editorEnabled && typeof window !== 'undefined') {
|
|
477
|
+
void import('./monaco-editor').then(mod => mod.init())
|
|
478
|
+
}
|
|
479
|
+
}, [flags.editorEnabled])
|
|
480
|
+
|
|
481
|
+
return <FlagsContext.Provider value={flags}>
|
|
482
|
+
{children}
|
|
483
|
+
</FlagsContext.Provider>
|
|
484
|
+
}
|
|
485
|
+
```
|
|
486
|
+
|
|
487
|
+
The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
|
|
488
|
+
|
|
489
|
+
---
|
|
490
|
+
|
|
491
|
+
## 3. Server-Side Performance
|
|
492
|
+
|
|
493
|
+
**Impact: HIGH**
|
|
494
|
+
|
|
495
|
+
Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
|
|
496
|
+
|
|
497
|
+
### 3.1 Cross-Request LRU Caching
|
|
498
|
+
|
|
499
|
+
`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.
|
|
500
|
+
|
|
501
|
+
**Implementation:**
|
|
502
|
+
|
|
503
|
+
```typescript
|
|
504
|
+
import { LRUCache } from 'lru-cache'
|
|
505
|
+
|
|
506
|
+
const cache = new LRUCache<string, any>({
|
|
507
|
+
max: 1000,
|
|
508
|
+
ttl: 5 * 60 * 1000 // 5 minutes
|
|
509
|
+
})
|
|
510
|
+
|
|
511
|
+
export async function getUser(id: string) {
|
|
512
|
+
const cached = cache.get(id)
|
|
513
|
+
if (cached) return cached
|
|
514
|
+
|
|
515
|
+
const user = await db.user.findUnique({ where: { id } })
|
|
516
|
+
cache.set(id, user)
|
|
517
|
+
return user
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Request 1: DB query, result cached
|
|
521
|
+
// Request 2: cache hit, no DB query
|
|
522
|
+
```
|
|
523
|
+
|
|
524
|
+
Use when sequential user actions hit multiple endpoints needing the same data within seconds. In serverless, consider Redis for cross-process caching.
|
|
525
|
+
|
|
526
|
+
Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
|
527
|
+
|
|
528
|
+
### 3.2 Minimize Serialization at RSC Boundaries
|
|
529
|
+
|
|
530
|
+
The React Server/Client boundary serializes all object properties. Only pass fields that the client actually uses.
|
|
531
|
+
|
|
532
|
+
**Incorrect: serializes all 50 fields**
|
|
533
|
+
|
|
534
|
+
```tsx
|
|
535
|
+
async function Page() {
|
|
536
|
+
const user = await fetchUser() // 50 fields
|
|
537
|
+
return <Profile user={user} />
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
'use client'
|
|
541
|
+
function Profile({ user }: { user: User }) {
|
|
542
|
+
return <div>{user.name}</div> // uses 1 field
|
|
543
|
+
}
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
**Correct: serializes only 1 field**
|
|
547
|
+
|
|
548
|
+
```tsx
|
|
549
|
+
async function Page() {
|
|
550
|
+
const user = await fetchUser()
|
|
551
|
+
return <Profile name={user.name} />
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
'use client'
|
|
555
|
+
function Profile({ name }: { name: string }) {
|
|
556
|
+
return <div>{name}</div>
|
|
557
|
+
}
|
|
558
|
+
```
|
|
559
|
+
|
|
560
|
+
### 3.3 Parallel Data Fetching with Component Composition
|
|
561
|
+
|
|
562
|
+
React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.
|
|
563
|
+
|
|
564
|
+
**Incorrect: Sidebar waits for Page's fetch to complete**
|
|
565
|
+
|
|
566
|
+
```tsx
|
|
567
|
+
export default async function Page() {
|
|
568
|
+
const header = await fetchHeader()
|
|
569
|
+
return (
|
|
570
|
+
<div>
|
|
571
|
+
<div>{header}</div>
|
|
572
|
+
<Sidebar />
|
|
573
|
+
</div>
|
|
574
|
+
)
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async function Sidebar() {
|
|
578
|
+
const items = await fetchSidebarItems()
|
|
579
|
+
return <nav>{items.map(renderItem)}</nav>
|
|
580
|
+
}
|
|
581
|
+
```
|
|
582
|
+
|
|
583
|
+
**Correct: both fetch simultaneously**
|
|
584
|
+
|
|
585
|
+
```tsx
|
|
586
|
+
async function Header() {
|
|
587
|
+
const data = await fetchHeader()
|
|
588
|
+
return <div>{data}</div>
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
async function Sidebar() {
|
|
592
|
+
const items = await fetchSidebarItems()
|
|
593
|
+
return <nav>{items.map(renderItem)}</nav>
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
export default function Page() {
|
|
597
|
+
return (
|
|
598
|
+
<div>
|
|
599
|
+
<Header />
|
|
600
|
+
<Sidebar />
|
|
601
|
+
</div>
|
|
602
|
+
)
|
|
603
|
+
}
|
|
604
|
+
```
|
|
605
|
+
|
|
606
|
+
**Alternative with children prop:**
|
|
607
|
+
|
|
608
|
+
```tsx
|
|
609
|
+
async function Layout({ children }: { children: ReactNode }) {
|
|
610
|
+
const header = await fetchHeader()
|
|
611
|
+
return (
|
|
612
|
+
<div>
|
|
613
|
+
<div>{header}</div>
|
|
614
|
+
{children}
|
|
615
|
+
</div>
|
|
616
|
+
)
|
|
617
|
+
}
|
|
618
|
+
|
|
619
|
+
async function Sidebar() {
|
|
620
|
+
const items = await fetchSidebarItems()
|
|
621
|
+
return <nav>{items.map(renderItem)}</nav>
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
export default function Page() {
|
|
625
|
+
return (
|
|
626
|
+
<Layout>
|
|
627
|
+
<Sidebar />
|
|
628
|
+
</Layout>
|
|
629
|
+
)
|
|
630
|
+
}
|
|
631
|
+
```
|
|
632
|
+
|
|
633
|
+
### 3.4 Per-Request Deduplication with React.cache()
|
|
634
|
+
|
|
635
|
+
Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.
|
|
636
|
+
|
|
637
|
+
**Usage:**
|
|
638
|
+
|
|
639
|
+
```typescript
|
|
640
|
+
import { cache } from 'react'
|
|
641
|
+
|
|
642
|
+
export const getCurrentUser = cache(async () => {
|
|
643
|
+
const session = await auth()
|
|
644
|
+
if (!session?.user?.id) return null
|
|
645
|
+
return await db.user.findUnique({
|
|
646
|
+
where: { id: session.user.id }
|
|
647
|
+
})
|
|
648
|
+
})
|
|
649
|
+
```
|
|
650
|
+
|
|
651
|
+
Within a single request, multiple calls to `getCurrentUser()` execute the query only once.
|
|
652
|
+
|
|
653
|
+
---
|
|
654
|
+
|
|
655
|
+
## 4. Client-Side Data Fetching
|
|
656
|
+
|
|
657
|
+
**Impact: MEDIUM-HIGH**
|
|
658
|
+
|
|
659
|
+
Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
|
|
660
|
+
|
|
661
|
+
### 4.1 Deduplicate Global Event Listeners
|
|
662
|
+
|
|
663
|
+
Use `useSWRSubscription()` to share global event listeners across component instances.
|
|
664
|
+
|
|
665
|
+
**Incorrect: N instances = N listeners**
|
|
666
|
+
|
|
667
|
+
```tsx
|
|
668
|
+
function useKeyboardShortcut(key: string, callback: () => void) {
|
|
669
|
+
useEffect(() => {
|
|
670
|
+
const handler = (e: KeyboardEvent) => {
|
|
671
|
+
if (e.metaKey && e.key === key) {
|
|
672
|
+
callback()
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
window.addEventListener('keydown', handler)
|
|
676
|
+
return () => window.removeEventListener('keydown', handler)
|
|
677
|
+
}, [key, callback])
|
|
678
|
+
}
|
|
679
|
+
```
|
|
680
|
+
|
|
681
|
+
When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
|
|
682
|
+
|
|
683
|
+
**Correct: N instances = 1 listener**
|
|
684
|
+
|
|
685
|
+
```tsx
|
|
686
|
+
import useSWRSubscription from 'swr/subscription'
|
|
687
|
+
|
|
688
|
+
// Module-level Map to track callbacks per key
|
|
689
|
+
const keyCallbacks = new Map<string, Set<() => void>>()
|
|
690
|
+
|
|
691
|
+
function useKeyboardShortcut(key: string, callback: () => void) {
|
|
692
|
+
// Register this callback in the Map
|
|
693
|
+
useEffect(() => {
|
|
694
|
+
if (!keyCallbacks.has(key)) {
|
|
695
|
+
keyCallbacks.set(key, new Set())
|
|
696
|
+
}
|
|
697
|
+
keyCallbacks.get(key)!.add(callback)
|
|
698
|
+
|
|
699
|
+
return () => {
|
|
700
|
+
const set = keyCallbacks.get(key)
|
|
701
|
+
if (set) {
|
|
702
|
+
set.delete(callback)
|
|
703
|
+
if (set.size === 0) {
|
|
704
|
+
keyCallbacks.delete(key)
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}, [key, callback])
|
|
709
|
+
|
|
710
|
+
useSWRSubscription('global-keydown', () => {
|
|
711
|
+
const handler = (e: KeyboardEvent) => {
|
|
712
|
+
if (e.metaKey && keyCallbacks.has(e.key)) {
|
|
713
|
+
keyCallbacks.get(e.key)!.forEach(cb => cb())
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
window.addEventListener('keydown', handler)
|
|
717
|
+
return () => window.removeEventListener('keydown', handler)
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
function Profile() {
|
|
722
|
+
// Multiple shortcuts will share the same listener
|
|
723
|
+
useKeyboardShortcut('p', () => { /* ... */ })
|
|
724
|
+
useKeyboardShortcut('k', () => { /* ... */ })
|
|
725
|
+
// ...
|
|
726
|
+
}
|
|
727
|
+
```
|
|
728
|
+
|
|
729
|
+
### 4.2 Use SWR for Automatic Deduplication
|
|
730
|
+
|
|
731
|
+
SWR enables request deduplication, caching, and revalidation across component instances.
|
|
732
|
+
|
|
733
|
+
**Incorrect: no deduplication, each instance fetches**
|
|
734
|
+
|
|
735
|
+
```tsx
|
|
736
|
+
function UserList() {
|
|
737
|
+
const [users, setUsers] = useState([])
|
|
738
|
+
useEffect(() => {
|
|
739
|
+
fetch('/api/users')
|
|
740
|
+
.then(r => r.json())
|
|
741
|
+
.then(setUsers)
|
|
742
|
+
}, [])
|
|
743
|
+
}
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
**Correct: multiple instances share one request**
|
|
747
|
+
|
|
748
|
+
```tsx
|
|
749
|
+
import useSWR from 'swr'
|
|
750
|
+
|
|
751
|
+
function UserList() {
|
|
752
|
+
const { data: users } = useSWR('/api/users', fetcher)
|
|
753
|
+
}
|
|
754
|
+
```
|
|
755
|
+
|
|
756
|
+
**For immutable data:**
|
|
757
|
+
|
|
758
|
+
```tsx
|
|
759
|
+
import { useImmutableSWR } from '@/lib/swr'
|
|
760
|
+
|
|
761
|
+
function StaticContent() {
|
|
762
|
+
const { data } = useImmutableSWR('/api/config', fetcher)
|
|
763
|
+
}
|
|
764
|
+
```
|
|
765
|
+
|
|
766
|
+
**For mutations:**
|
|
767
|
+
|
|
768
|
+
```tsx
|
|
769
|
+
import { useSWRMutation } from 'swr/mutation'
|
|
770
|
+
|
|
771
|
+
function UpdateButton() {
|
|
772
|
+
const { trigger } = useSWRMutation('/api/user', updateUser)
|
|
773
|
+
return <button onClick={() => trigger()}>Update</button>
|
|
774
|
+
}
|
|
775
|
+
```
|
|
776
|
+
|
|
777
|
+
Reference: [https://swr.vercel.app](https://swr.vercel.app)
|
|
778
|
+
|
|
779
|
+
---
|
|
780
|
+
|
|
781
|
+
## 5. Re-render Optimization
|
|
782
|
+
|
|
783
|
+
**Impact: MEDIUM**
|
|
784
|
+
|
|
785
|
+
Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
|
|
786
|
+
|
|
787
|
+
### 5.1 Defer State Reads to Usage Point
|
|
788
|
+
|
|
789
|
+
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
|
790
|
+
|
|
791
|
+
**Incorrect: subscribes to all searchParams changes**
|
|
792
|
+
|
|
793
|
+
```tsx
|
|
794
|
+
function ShareButton({ chatId }: { chatId: string }) {
|
|
795
|
+
const searchParams = useSearchParams()
|
|
796
|
+
|
|
797
|
+
const handleShare = () => {
|
|
798
|
+
const ref = searchParams.get('ref')
|
|
799
|
+
shareChat(chatId, { ref })
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
return <button onClick={handleShare}>Share</button>
|
|
803
|
+
}
|
|
804
|
+
```
|
|
805
|
+
|
|
806
|
+
**Correct: reads on demand, no subscription**
|
|
807
|
+
|
|
808
|
+
```tsx
|
|
809
|
+
function ShareButton({ chatId }: { chatId: string }) {
|
|
810
|
+
const handleShare = () => {
|
|
811
|
+
const params = new URLSearchParams(window.location.search)
|
|
812
|
+
const ref = params.get('ref')
|
|
813
|
+
shareChat(chatId, { ref })
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
return <button onClick={handleShare}>Share</button>
|
|
817
|
+
}
|
|
818
|
+
```
|
|
819
|
+
|
|
820
|
+
### 5.2 Extract to Memoized Components
|
|
821
|
+
|
|
822
|
+
Extract expensive work into memoized components to enable early returns before computation.
|
|
823
|
+
|
|
824
|
+
**Incorrect: computes avatar even when loading**
|
|
825
|
+
|
|
826
|
+
```tsx
|
|
827
|
+
function Profile({ user, loading }: Props) {
|
|
828
|
+
const avatar = useMemo(() => {
|
|
829
|
+
const id = computeAvatarId(user)
|
|
830
|
+
return <Avatar id={id} />
|
|
831
|
+
}, [user])
|
|
832
|
+
|
|
833
|
+
if (loading) return <Skeleton />
|
|
834
|
+
return <div>{avatar}</div>
|
|
835
|
+
}
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
**Correct: skips computation when loading**
|
|
839
|
+
|
|
840
|
+
```tsx
|
|
841
|
+
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
|
842
|
+
const id = useMemo(() => computeAvatarId(user), [user])
|
|
843
|
+
return <Avatar id={id} />
|
|
844
|
+
})
|
|
845
|
+
|
|
846
|
+
function Profile({ user, loading }: Props) {
|
|
847
|
+
if (loading) return <Skeleton />
|
|
848
|
+
return (
|
|
849
|
+
<div>
|
|
850
|
+
<UserAvatar user={user} />
|
|
851
|
+
</div>
|
|
852
|
+
)
|
|
853
|
+
}
|
|
854
|
+
```
|
|
855
|
+
|
|
856
|
+
### 5.3 Narrow Effect Dependencies
|
|
857
|
+
|
|
858
|
+
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
|
859
|
+
|
|
860
|
+
**Incorrect: re-runs on any user field change**
|
|
861
|
+
|
|
862
|
+
```tsx
|
|
863
|
+
useEffect(() => {
|
|
864
|
+
console.log(user.id)
|
|
865
|
+
}, [user])
|
|
866
|
+
```
|
|
867
|
+
|
|
868
|
+
**Correct: re-runs only when id changes**
|
|
869
|
+
|
|
870
|
+
```tsx
|
|
871
|
+
useEffect(() => {
|
|
872
|
+
console.log(user.id)
|
|
873
|
+
}, [user.id])
|
|
874
|
+
```
|
|
875
|
+
|
|
876
|
+
**For derived state, compute outside effect:**
|
|
877
|
+
|
|
878
|
+
```tsx
|
|
879
|
+
// Incorrect: runs on width=767, 766, 765...
|
|
880
|
+
useEffect(() => {
|
|
881
|
+
if (width < 768) {
|
|
882
|
+
enableMobileMode()
|
|
883
|
+
}
|
|
884
|
+
}, [width])
|
|
885
|
+
|
|
886
|
+
// Correct: runs only on boolean transition
|
|
887
|
+
const isMobile = width < 768
|
|
888
|
+
useEffect(() => {
|
|
889
|
+
if (isMobile) {
|
|
890
|
+
enableMobileMode()
|
|
891
|
+
}
|
|
892
|
+
}, [isMobile])
|
|
893
|
+
```
|
|
894
|
+
|
|
895
|
+
### 5.4 Subscribe to Derived State
|
|
896
|
+
|
|
897
|
+
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
|
898
|
+
|
|
899
|
+
**Incorrect: re-renders on every pixel change**
|
|
900
|
+
|
|
901
|
+
```tsx
|
|
902
|
+
function Sidebar() {
|
|
903
|
+
const width = useWindowWidth() // updates continuously
|
|
904
|
+
const isMobile = width < 768
|
|
905
|
+
return <nav className={isMobile ? 'mobile' : 'desktop'}>
|
|
906
|
+
}
|
|
907
|
+
```
|
|
908
|
+
|
|
909
|
+
**Correct: re-renders only when boolean changes**
|
|
910
|
+
|
|
911
|
+
```tsx
|
|
912
|
+
function Sidebar() {
|
|
913
|
+
const isMobile = useMediaQuery('(max-width: 767px)')
|
|
914
|
+
return <nav className={isMobile ? 'mobile' : 'desktop'}>
|
|
915
|
+
}
|
|
916
|
+
```
|
|
917
|
+
|
|
918
|
+
### 5.5 Use Lazy State Initialization
|
|
919
|
+
|
|
920
|
+
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.
|
|
921
|
+
|
|
922
|
+
**Incorrect: runs on every render**
|
|
923
|
+
|
|
924
|
+
```tsx
|
|
925
|
+
function FilteredList({ items }: { items: Item[] }) {
|
|
926
|
+
// buildSearchIndex() runs on EVERY render, even after initialization
|
|
927
|
+
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
|
928
|
+
const [query, setQuery] = useState('')
|
|
929
|
+
|
|
930
|
+
// When query changes, buildSearchIndex runs again unnecessarily
|
|
931
|
+
return <SearchResults index={searchIndex} query={query} />
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
function UserProfile() {
|
|
935
|
+
// JSON.parse runs on every render
|
|
936
|
+
const [settings, setSettings] = useState(
|
|
937
|
+
JSON.parse(localStorage.getItem('settings') || '{}')
|
|
938
|
+
)
|
|
939
|
+
|
|
940
|
+
return <SettingsForm settings={settings} onChange={setSettings} />
|
|
941
|
+
}
|
|
942
|
+
```
|
|
943
|
+
|
|
944
|
+
**Correct: runs only once**
|
|
945
|
+
|
|
946
|
+
```tsx
|
|
947
|
+
function FilteredList({ items }: { items: Item[] }) {
|
|
948
|
+
// buildSearchIndex() runs ONLY on initial render
|
|
949
|
+
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
|
950
|
+
const [query, setQuery] = useState('')
|
|
951
|
+
|
|
952
|
+
return <SearchResults index={searchIndex} query={query} />
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
function UserProfile() {
|
|
956
|
+
// JSON.parse runs only on initial render
|
|
957
|
+
const [settings, setSettings] = useState(() => {
|
|
958
|
+
const stored = localStorage.getItem('settings')
|
|
959
|
+
return stored ? JSON.parse(stored) : {}
|
|
960
|
+
})
|
|
961
|
+
|
|
962
|
+
return <SettingsForm settings={settings} onChange={setSettings} />
|
|
963
|
+
}
|
|
964
|
+
```
|
|
965
|
+
|
|
966
|
+
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
|
967
|
+
|
|
968
|
+
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
|
969
|
+
|
|
970
|
+
### 5.6 Use Transitions for Non-Urgent Updates
|
|
971
|
+
|
|
972
|
+
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
|
973
|
+
|
|
974
|
+
**Incorrect: blocks UI on every scroll**
|
|
975
|
+
|
|
976
|
+
```tsx
|
|
977
|
+
function ScrollTracker() {
|
|
978
|
+
const [scrollY, setScrollY] = useState(0)
|
|
979
|
+
useEffect(() => {
|
|
980
|
+
const handler = () => setScrollY(window.scrollY)
|
|
981
|
+
window.addEventListener('scroll', handler, { passive: true })
|
|
982
|
+
return () => window.removeEventListener('scroll', handler)
|
|
983
|
+
}, [])
|
|
984
|
+
}
|
|
985
|
+
```
|
|
986
|
+
|
|
987
|
+
**Correct: non-blocking updates**
|
|
988
|
+
|
|
989
|
+
```tsx
|
|
990
|
+
import { startTransition } from 'react'
|
|
991
|
+
|
|
992
|
+
function ScrollTracker() {
|
|
993
|
+
const [scrollY, setScrollY] = useState(0)
|
|
994
|
+
useEffect(() => {
|
|
995
|
+
const handler = () => {
|
|
996
|
+
startTransition(() => setScrollY(window.scrollY))
|
|
997
|
+
}
|
|
998
|
+
window.addEventListener('scroll', handler, { passive: true })
|
|
999
|
+
return () => window.removeEventListener('scroll', handler)
|
|
1000
|
+
}, [])
|
|
1001
|
+
}
|
|
1002
|
+
```
|
|
1003
|
+
|
|
1004
|
+
---
|
|
1005
|
+
|
|
1006
|
+
## 6. Rendering Performance
|
|
1007
|
+
|
|
1008
|
+
**Impact: MEDIUM**
|
|
1009
|
+
|
|
1010
|
+
Optimizing the rendering process reduces the work the browser needs to do.
|
|
1011
|
+
|
|
1012
|
+
### 6.1 Animate SVG Wrapper Instead of SVG Element
|
|
1013
|
+
|
|
1014
|
+
Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
|
|
1015
|
+
|
|
1016
|
+
**Incorrect: animating SVG directly - no hardware acceleration**
|
|
1017
|
+
|
|
1018
|
+
```tsx
|
|
1019
|
+
function LoadingSpinner() {
|
|
1020
|
+
return (
|
|
1021
|
+
<svg
|
|
1022
|
+
className="animate-spin"
|
|
1023
|
+
width="24"
|
|
1024
|
+
height="24"
|
|
1025
|
+
viewBox="0 0 24 24"
|
|
1026
|
+
>
|
|
1027
|
+
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
|
1028
|
+
</svg>
|
|
1029
|
+
)
|
|
1030
|
+
}
|
|
1031
|
+
```
|
|
1032
|
+
|
|
1033
|
+
**Correct: animating wrapper div - hardware accelerated**
|
|
1034
|
+
|
|
1035
|
+
```tsx
|
|
1036
|
+
function LoadingSpinner() {
|
|
1037
|
+
return (
|
|
1038
|
+
<div className="animate-spin">
|
|
1039
|
+
<svg
|
|
1040
|
+
width="24"
|
|
1041
|
+
height="24"
|
|
1042
|
+
viewBox="0 0 24 24"
|
|
1043
|
+
>
|
|
1044
|
+
<circle cx="12" cy="12" r="10" stroke="currentColor" />
|
|
1045
|
+
</svg>
|
|
1046
|
+
</div>
|
|
1047
|
+
)
|
|
1048
|
+
}
|
|
1049
|
+
```
|
|
1050
|
+
|
|
1051
|
+
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.
|
|
1052
|
+
|
|
1053
|
+
### 6.2 CSS content-visibility for Long Lists
|
|
1054
|
+
|
|
1055
|
+
Apply `content-visibility: auto` to defer off-screen rendering.
|
|
1056
|
+
|
|
1057
|
+
**CSS:**
|
|
1058
|
+
|
|
1059
|
+
```css
|
|
1060
|
+
.message-item {
|
|
1061
|
+
content-visibility: auto;
|
|
1062
|
+
contain-intrinsic-size: 0 80px;
|
|
1063
|
+
}
|
|
1064
|
+
```
|
|
1065
|
+
|
|
1066
|
+
**Example:**
|
|
1067
|
+
|
|
1068
|
+
```tsx
|
|
1069
|
+
function MessageList({ messages }: { messages: Message[] }) {
|
|
1070
|
+
return (
|
|
1071
|
+
<div className="overflow-y-auto h-screen">
|
|
1072
|
+
{messages.map(msg => (
|
|
1073
|
+
<div key={msg.id} className="message-item">
|
|
1074
|
+
<Avatar user={msg.author} />
|
|
1075
|
+
<div>{msg.content}</div>
|
|
1076
|
+
</div>
|
|
1077
|
+
))}
|
|
1078
|
+
</div>
|
|
1079
|
+
)
|
|
1080
|
+
}
|
|
1081
|
+
```
|
|
1082
|
+
|
|
1083
|
+
For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
|
|
1084
|
+
|
|
1085
|
+
### 6.3 Hoist Static JSX Elements
|
|
1086
|
+
|
|
1087
|
+
Extract static JSX outside components to avoid re-creation.
|
|
1088
|
+
|
|
1089
|
+
**Incorrect: recreates element every render**
|
|
1090
|
+
|
|
1091
|
+
```tsx
|
|
1092
|
+
function LoadingSkeleton() {
|
|
1093
|
+
return <div className="animate-pulse h-20 bg-gray-200" />
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
function Container() {
|
|
1097
|
+
return (
|
|
1098
|
+
<div>
|
|
1099
|
+
{loading && <LoadingSkeleton />}
|
|
1100
|
+
</div>
|
|
1101
|
+
)
|
|
1102
|
+
}
|
|
1103
|
+
```
|
|
1104
|
+
|
|
1105
|
+
**Correct: reuses same element**
|
|
1106
|
+
|
|
1107
|
+
```tsx
|
|
1108
|
+
const loadingSkeleton = (
|
|
1109
|
+
<div className="animate-pulse h-20 bg-gray-200" />
|
|
1110
|
+
)
|
|
1111
|
+
|
|
1112
|
+
function Container() {
|
|
1113
|
+
return (
|
|
1114
|
+
<div>
|
|
1115
|
+
{loading && loadingSkeleton}
|
|
1116
|
+
</div>
|
|
1117
|
+
)
|
|
1118
|
+
}
|
|
1119
|
+
```
|
|
1120
|
+
|
|
1121
|
+
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
|
|
1122
|
+
|
|
1123
|
+
### 6.4 Optimize SVG Precision
|
|
1124
|
+
|
|
1125
|
+
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
|
|
1126
|
+
|
|
1127
|
+
**Incorrect: excessive precision**
|
|
1128
|
+
|
|
1129
|
+
```svg
|
|
1130
|
+
<path d="M 10.293847 20.847362 L 30.938472 40.192837" />
|
|
1131
|
+
```
|
|
1132
|
+
|
|
1133
|
+
**Correct: 1 decimal place**
|
|
1134
|
+
|
|
1135
|
+
```svg
|
|
1136
|
+
<path d="M 10.3 20.8 L 30.9 40.2" />
|
|
1137
|
+
```
|
|
1138
|
+
|
|
1139
|
+
**Automate with SVGO:**
|
|
1140
|
+
|
|
1141
|
+
```bash
|
|
1142
|
+
npx svgo --precision=1 --multipass icon.svg
|
|
1143
|
+
```
|
|
1144
|
+
|
|
1145
|
+
### 6.5 Prevent Hydration Mismatch Without Flickering
|
|
1146
|
+
|
|
1147
|
+
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.
|
|
1148
|
+
|
|
1149
|
+
**Incorrect: breaks SSR**
|
|
1150
|
+
|
|
1151
|
+
```tsx
|
|
1152
|
+
function ThemeWrapper({ children }: { children: ReactNode }) {
|
|
1153
|
+
// localStorage is not available on server - throws error
|
|
1154
|
+
const theme = localStorage.getItem('theme') || 'light'
|
|
1155
|
+
|
|
1156
|
+
return (
|
|
1157
|
+
<div className={theme}>
|
|
1158
|
+
{children}
|
|
1159
|
+
</div>
|
|
1160
|
+
)
|
|
1161
|
+
}
|
|
1162
|
+
```
|
|
1163
|
+
|
|
1164
|
+
Server-side rendering will fail because `localStorage` is undefined.
|
|
1165
|
+
|
|
1166
|
+
**Incorrect: visual flickering**
|
|
1167
|
+
|
|
1168
|
+
```tsx
|
|
1169
|
+
function ThemeWrapper({ children }: { children: ReactNode }) {
|
|
1170
|
+
const [theme, setTheme] = useState('light')
|
|
1171
|
+
|
|
1172
|
+
useEffect(() => {
|
|
1173
|
+
// Runs after hydration - causes visible flash
|
|
1174
|
+
const stored = localStorage.getItem('theme')
|
|
1175
|
+
if (stored) {
|
|
1176
|
+
setTheme(stored)
|
|
1177
|
+
}
|
|
1178
|
+
}, [])
|
|
1179
|
+
|
|
1180
|
+
return (
|
|
1181
|
+
<div className={theme}>
|
|
1182
|
+
{children}
|
|
1183
|
+
</div>
|
|
1184
|
+
)
|
|
1185
|
+
}
|
|
1186
|
+
```
|
|
1187
|
+
|
|
1188
|
+
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
|
|
1189
|
+
|
|
1190
|
+
**Correct: no flicker, no hydration mismatch**
|
|
1191
|
+
|
|
1192
|
+
```tsx
|
|
1193
|
+
function ThemeWrapper({ children }: { children: ReactNode }) {
|
|
1194
|
+
return (
|
|
1195
|
+
<>
|
|
1196
|
+
<div id="theme-wrapper">
|
|
1197
|
+
{children}
|
|
1198
|
+
</div>
|
|
1199
|
+
<script
|
|
1200
|
+
dangerouslySetInnerHTML={{
|
|
1201
|
+
__html: `
|
|
1202
|
+
(function() {
|
|
1203
|
+
try {
|
|
1204
|
+
var theme = localStorage.getItem('theme') || 'light';
|
|
1205
|
+
var el = document.getElementById('theme-wrapper');
|
|
1206
|
+
if (el) el.className = theme;
|
|
1207
|
+
} catch (e) {}
|
|
1208
|
+
})();
|
|
1209
|
+
`,
|
|
1210
|
+
}}
|
|
1211
|
+
/>
|
|
1212
|
+
</>
|
|
1213
|
+
)
|
|
1214
|
+
}
|
|
1215
|
+
```
|
|
1216
|
+
|
|
1217
|
+
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
|
|
1218
|
+
|
|
1219
|
+
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.
|
|
1220
|
+
|
|
1221
|
+
### 6.6 Use Activity Component for Show/Hide
|
|
1222
|
+
|
|
1223
|
+
Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
|
|
1224
|
+
|
|
1225
|
+
**Usage:**
|
|
1226
|
+
|
|
1227
|
+
```tsx
|
|
1228
|
+
import { Activity } from 'react'
|
|
1229
|
+
|
|
1230
|
+
function Dropdown({ isOpen }: Props) {
|
|
1231
|
+
return (
|
|
1232
|
+
<Activity mode={isOpen ? 'visible' : 'hidden'}>
|
|
1233
|
+
<ExpensiveMenu />
|
|
1234
|
+
</Activity>
|
|
1235
|
+
)
|
|
1236
|
+
}
|
|
1237
|
+
```
|
|
1238
|
+
|
|
1239
|
+
Avoids expensive re-renders and state loss.
|
|
1240
|
+
|
|
1241
|
+
### 6.7 Use Explicit Conditional Rendering
|
|
1242
|
+
|
|
1243
|
+
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
|
|
1244
|
+
|
|
1245
|
+
**Incorrect: renders "0" when count is 0**
|
|
1246
|
+
|
|
1247
|
+
```tsx
|
|
1248
|
+
function Badge({ count }: { count: number }) {
|
|
1249
|
+
return (
|
|
1250
|
+
<div>
|
|
1251
|
+
{count && <span className="badge">{count}</span>}
|
|
1252
|
+
</div>
|
|
1253
|
+
)
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
// When count = 0, renders: <div>0</div>
|
|
1257
|
+
// When count = 5, renders: <div><span class="badge">5</span></div>
|
|
1258
|
+
```
|
|
1259
|
+
|
|
1260
|
+
**Correct: renders nothing when count is 0**
|
|
1261
|
+
|
|
1262
|
+
```tsx
|
|
1263
|
+
function Badge({ count }: { count: number }) {
|
|
1264
|
+
return (
|
|
1265
|
+
<div>
|
|
1266
|
+
{count > 0 ? <span className="badge">{count}</span> : null}
|
|
1267
|
+
</div>
|
|
1268
|
+
)
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
// When count = 0, renders: <div></div>
|
|
1272
|
+
// When count = 5, renders: <div><span class="badge">5</span></div>
|
|
1273
|
+
```
|
|
1274
|
+
|
|
1275
|
+
---
|
|
1276
|
+
|
|
1277
|
+
## 7. JavaScript Performance
|
|
1278
|
+
|
|
1279
|
+
**Impact: LOW-MEDIUM**
|
|
1280
|
+
|
|
1281
|
+
Micro-optimizations for hot paths can add up to meaningful improvements.
|
|
1282
|
+
|
|
1283
|
+
### 7.1 Batch DOM CSS Changes
|
|
1284
|
+
|
|
1285
|
+
Avoid changing styles one property at a time. Group multiple CSS changes together via classes or `cssText` to minimize browser reflows.
|
|
1286
|
+
|
|
1287
|
+
**Incorrect: multiple reflows**
|
|
1288
|
+
|
|
1289
|
+
```typescript
|
|
1290
|
+
function updateElementStyles(element: HTMLElement) {
|
|
1291
|
+
// Each line triggers a reflow
|
|
1292
|
+
element.style.width = '100px'
|
|
1293
|
+
element.style.height = '200px'
|
|
1294
|
+
element.style.backgroundColor = 'blue'
|
|
1295
|
+
element.style.border = '1px solid black'
|
|
1296
|
+
}
|
|
1297
|
+
```
|
|
1298
|
+
|
|
1299
|
+
**Correct: add class - single reflow**
|
|
1300
|
+
|
|
1301
|
+
```typescript
|
|
1302
|
+
// CSS file
|
|
1303
|
+
.highlighted-box {
|
|
1304
|
+
width: 100px;
|
|
1305
|
+
height: 200px;
|
|
1306
|
+
background-color: blue;
|
|
1307
|
+
border: 1px solid black;
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
// JavaScript
|
|
1311
|
+
function updateElementStyles(element: HTMLElement) {
|
|
1312
|
+
element.classList.add('highlighted-box')
|
|
1313
|
+
}
|
|
1314
|
+
```
|
|
1315
|
+
|
|
1316
|
+
**Correct: change cssText - single reflow**
|
|
1317
|
+
|
|
1318
|
+
```typescript
|
|
1319
|
+
function updateElementStyles(element: HTMLElement) {
|
|
1320
|
+
element.style.cssText = `
|
|
1321
|
+
width: 100px;
|
|
1322
|
+
height: 200px;
|
|
1323
|
+
background-color: blue;
|
|
1324
|
+
border: 1px solid black;
|
|
1325
|
+
`
|
|
1326
|
+
}
|
|
1327
|
+
```
|
|
1328
|
+
|
|
1329
|
+
**React example:**
|
|
1330
|
+
|
|
1331
|
+
```tsx
|
|
1332
|
+
// Incorrect: changing styles one by one
|
|
1333
|
+
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
|
1334
|
+
const ref = useRef<HTMLDivElement>(null)
|
|
1335
|
+
|
|
1336
|
+
useEffect(() => {
|
|
1337
|
+
if (ref.current && isHighlighted) {
|
|
1338
|
+
ref.current.style.width = '100px'
|
|
1339
|
+
ref.current.style.height = '200px'
|
|
1340
|
+
ref.current.style.backgroundColor = 'blue'
|
|
1341
|
+
}
|
|
1342
|
+
}, [isHighlighted])
|
|
1343
|
+
|
|
1344
|
+
return <div ref={ref}>Content</div>
|
|
1345
|
+
}
|
|
1346
|
+
|
|
1347
|
+
// Correct: toggle class
|
|
1348
|
+
function Box({ isHighlighted }: { isHighlighted: boolean }) {
|
|
1349
|
+
return (
|
|
1350
|
+
<div className={isHighlighted ? 'highlighted-box' : ''}>
|
|
1351
|
+
Content
|
|
1352
|
+
</div>
|
|
1353
|
+
)
|
|
1354
|
+
}
|
|
1355
|
+
```
|
|
1356
|
+
|
|
1357
|
+
Prefer CSS classes over inline styles when possible. Classes are cached by the browser and provide better separation of concerns.
|
|
1358
|
+
|
|
1359
|
+
### 7.2 Build Index Maps for Repeated Lookups
|
|
1360
|
+
|
|
1361
|
+
Multiple `.find()` calls by the same key should use a Map.
|
|
1362
|
+
|
|
1363
|
+
**Incorrect (O(n) per lookup):**
|
|
1364
|
+
|
|
1365
|
+
```typescript
|
|
1366
|
+
function processOrders(orders: Order[], users: User[]) {
|
|
1367
|
+
return orders.map(order => ({
|
|
1368
|
+
...order,
|
|
1369
|
+
user: users.find(u => u.id === order.userId)
|
|
1370
|
+
}))
|
|
1371
|
+
}
|
|
1372
|
+
```
|
|
1373
|
+
|
|
1374
|
+
**Correct (O(1) per lookup):**
|
|
1375
|
+
|
|
1376
|
+
```typescript
|
|
1377
|
+
function processOrders(orders: Order[], users: User[]) {
|
|
1378
|
+
const userById = new Map(users.map(u => [u.id, u]))
|
|
1379
|
+
|
|
1380
|
+
return orders.map(order => ({
|
|
1381
|
+
...order,
|
|
1382
|
+
user: userById.get(order.userId)
|
|
1383
|
+
}))
|
|
1384
|
+
}
|
|
1385
|
+
```
|
|
1386
|
+
|
|
1387
|
+
Build map once (O(n)), then all lookups are O(1).
|
|
1388
|
+
|
|
1389
|
+
For 1000 orders × 1000 users: 1M ops → 2K ops.
|
|
1390
|
+
|
|
1391
|
+
### 7.3 Cache Property Access in Loops
|
|
1392
|
+
|
|
1393
|
+
Cache object property lookups in hot paths.
|
|
1394
|
+
|
|
1395
|
+
**Incorrect: 3 lookups × N iterations**
|
|
1396
|
+
|
|
1397
|
+
```typescript
|
|
1398
|
+
for (let i = 0; i < arr.length; i++) {
|
|
1399
|
+
process(obj.config.settings.value)
|
|
1400
|
+
}
|
|
1401
|
+
```
|
|
1402
|
+
|
|
1403
|
+
**Correct: 1 lookup total**
|
|
1404
|
+
|
|
1405
|
+
```typescript
|
|
1406
|
+
const value = obj.config.settings.value
|
|
1407
|
+
const len = arr.length
|
|
1408
|
+
for (let i = 0; i < len; i++) {
|
|
1409
|
+
process(value)
|
|
1410
|
+
}
|
|
1411
|
+
```
|
|
1412
|
+
|
|
1413
|
+
### 7.4 Cache Repeated Function Calls
|
|
1414
|
+
|
|
1415
|
+
Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
|
|
1416
|
+
|
|
1417
|
+
**Incorrect: redundant computation**
|
|
1418
|
+
|
|
1419
|
+
```typescript
|
|
1420
|
+
function ProjectList({ projects }: { projects: Project[] }) {
|
|
1421
|
+
return (
|
|
1422
|
+
<div>
|
|
1423
|
+
{projects.map(project => {
|
|
1424
|
+
// slugify() called 100+ times for same project names
|
|
1425
|
+
const slug = slugify(project.name)
|
|
1426
|
+
|
|
1427
|
+
return <ProjectCard key={project.id} slug={slug} />
|
|
1428
|
+
})}
|
|
1429
|
+
</div>
|
|
1430
|
+
)
|
|
1431
|
+
}
|
|
1432
|
+
```
|
|
1433
|
+
|
|
1434
|
+
**Correct: cached results**
|
|
1435
|
+
|
|
1436
|
+
```typescript
|
|
1437
|
+
// Module-level cache
|
|
1438
|
+
const cachedSlugify = new Map<string, any>()
|
|
1439
|
+
|
|
1440
|
+
function getCachedSlug(text: string): string {
|
|
1441
|
+
if (cachedSlugify.has(text)) {
|
|
1442
|
+
return cachedSlugify.get(text)
|
|
1443
|
+
}
|
|
1444
|
+
const result = slugify(text)
|
|
1445
|
+
cachedSlugify.set(text, result)
|
|
1446
|
+
return result
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
function ProjectList({ projects }: { projects: Project[] }) {
|
|
1450
|
+
return (
|
|
1451
|
+
<div>
|
|
1452
|
+
{projects.map(project => {
|
|
1453
|
+
// Computed only once per unique project name
|
|
1454
|
+
const slug = getCachedSlug(project.name)
|
|
1455
|
+
|
|
1456
|
+
return <ProjectCard key={project.id} slug={slug} />
|
|
1457
|
+
})}
|
|
1458
|
+
</div>
|
|
1459
|
+
)
|
|
1460
|
+
}
|
|
1461
|
+
```
|
|
1462
|
+
|
|
1463
|
+
**Simpler pattern for single-value functions:**
|
|
1464
|
+
|
|
1465
|
+
```typescript
|
|
1466
|
+
let isLoggedInCache: boolean | null = null
|
|
1467
|
+
|
|
1468
|
+
function isLoggedIn(): boolean {
|
|
1469
|
+
if (isLoggedInCache !== null) {
|
|
1470
|
+
return isLoggedInCache
|
|
1471
|
+
}
|
|
1472
|
+
|
|
1473
|
+
isLoggedInCache = document.cookie.includes('auth=')
|
|
1474
|
+
return isLoggedInCache
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// Clear cache when auth changes
|
|
1478
|
+
function onAuthChange() {
|
|
1479
|
+
isLoggedInCache = null
|
|
1480
|
+
}
|
|
1481
|
+
```
|
|
1482
|
+
|
|
1483
|
+
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
|
1484
|
+
|
|
1485
|
+
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)
|
|
1486
|
+
|
|
1487
|
+
### 7.5 Cache Storage API Calls
|
|
1488
|
+
|
|
1489
|
+
`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
|
|
1490
|
+
|
|
1491
|
+
**Incorrect: reads storage on every call**
|
|
1492
|
+
|
|
1493
|
+
```typescript
|
|
1494
|
+
function getTheme() {
|
|
1495
|
+
return localStorage.getItem('theme') ?? 'light'
|
|
1496
|
+
}
|
|
1497
|
+
// Called 10 times = 10 storage reads
|
|
1498
|
+
```
|
|
1499
|
+
|
|
1500
|
+
**Correct: Map cache**
|
|
1501
|
+
|
|
1502
|
+
```typescript
|
|
1503
|
+
const storageCache = new Map<string, string | null>()
|
|
1504
|
+
|
|
1505
|
+
function getLocalStorage(key: string) {
|
|
1506
|
+
if (!storageCache.has(key)) {
|
|
1507
|
+
storageCache.set(key, localStorage.getItem(key))
|
|
1508
|
+
}
|
|
1509
|
+
return storageCache.get(key)
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
function setLocalStorage(key: string, value: string) {
|
|
1513
|
+
localStorage.setItem(key, value)
|
|
1514
|
+
storageCache.set(key, value) // keep cache in sync
|
|
1515
|
+
}
|
|
1516
|
+
```
|
|
1517
|
+
|
|
1518
|
+
Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
|
|
1519
|
+
|
|
1520
|
+
**Cache invalidation:**
|
|
1521
|
+
|
|
1522
|
+
```typescript
|
|
1523
|
+
window.addEventListener('storage', (e) => {
|
|
1524
|
+
if (e.key) storageCache.delete(e.key)
|
|
1525
|
+
})
|
|
1526
|
+
|
|
1527
|
+
document.addEventListener('visibilitychange', () => {
|
|
1528
|
+
if (document.visibilityState === 'visible') {
|
|
1529
|
+
storageCache.clear()
|
|
1530
|
+
}
|
|
1531
|
+
})
|
|
1532
|
+
```
|
|
1533
|
+
|
|
1534
|
+
### 7.6 Combine Multiple Array Iterations
|
|
1535
|
+
|
|
1536
|
+
Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
|
|
1537
|
+
|
|
1538
|
+
**Incorrect: 3 iterations**
|
|
1539
|
+
|
|
1540
|
+
```typescript
|
|
1541
|
+
const admins = users.filter(u => u.isAdmin)
|
|
1542
|
+
const testers = users.filter(u => u.isTester)
|
|
1543
|
+
const inactive = users.filter(u => !u.isActive)
|
|
1544
|
+
```
|
|
1545
|
+
|
|
1546
|
+
**Correct: 1 iteration**
|
|
1547
|
+
|
|
1548
|
+
```typescript
|
|
1549
|
+
const admins: User[] = []
|
|
1550
|
+
const testers: User[] = []
|
|
1551
|
+
const inactive: User[] = []
|
|
1552
|
+
|
|
1553
|
+
for (const user of users) {
|
|
1554
|
+
if (user.isAdmin) admins.push(user)
|
|
1555
|
+
if (user.isTester) testers.push(user)
|
|
1556
|
+
if (!user.isActive) inactive.push(user)
|
|
1557
|
+
}
|
|
1558
|
+
```
|
|
1559
|
+
|
|
1560
|
+
### 7.7 Early Length Check for Array Comparisons
|
|
1561
|
+
|
|
1562
|
+
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
|
|
1563
|
+
|
|
1564
|
+
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
|
|
1565
|
+
|
|
1566
|
+
**Incorrect: always runs expensive comparison**
|
|
1567
|
+
|
|
1568
|
+
```typescript
|
|
1569
|
+
function hasChanges(current: string[], original: string[]) {
|
|
1570
|
+
// Always sorts and joins, even when lengths differ
|
|
1571
|
+
return current.sort().join() !== original.sort().join()
|
|
1572
|
+
}
|
|
1573
|
+
```
|
|
1574
|
+
|
|
1575
|
+
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100.
|
|
1576
|
+
|
|
1577
|
+
**Correct (O(1) length check first):**
|
|
1578
|
+
|
|
1579
|
+
```typescript
|
|
1580
|
+
function hasChanges(current: string[], original: string[]) {
|
|
1581
|
+
// Early return if lengths differ
|
|
1582
|
+
if (current.length !== original.length) {
|
|
1583
|
+
return true
|
|
1584
|
+
}
|
|
1585
|
+
// Only sort when lengths match
|
|
1586
|
+
const currentSorted = current.toSorted()
|
|
1587
|
+
const originalSorted = original.toSorted()
|
|
1588
|
+
for (let i = 0; i < currentSorted.length; i++) {
|
|
1589
|
+
if (currentSorted[i] !== originalSorted[i]) {
|
|
1590
|
+
return true
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
return false
|
|
1594
|
+
}
|
|
1595
|
+
```
|
|
1596
|
+
|
|
1597
|
+
This approach avoids sorting when lengths differ, avoiding both computational overhead and memory consumption for joined strings.
|
|
1598
|
+
|
|
1599
|
+
### 7.8 Early Return from Functions
|
|
1600
|
+
|
|
1601
|
+
Return early when result is determined to skip unnecessary processing.
|
|
1602
|
+
|
|
1603
|
+
**Incorrect: processes all items even after finding answer**
|
|
1604
|
+
|
|
1605
|
+
```typescript
|
|
1606
|
+
function validateUsers(users: User[]) {
|
|
1607
|
+
let hasError = false
|
|
1608
|
+
let errorMessage = ''
|
|
1609
|
+
|
|
1610
|
+
for (const user of users) {
|
|
1611
|
+
if (!user.email) {
|
|
1612
|
+
hasError = true
|
|
1613
|
+
errorMessage = 'Email required'
|
|
1614
|
+
}
|
|
1615
|
+
if (!user.name) {
|
|
1616
|
+
hasError = true
|
|
1617
|
+
errorMessage = 'Name required'
|
|
1618
|
+
}
|
|
1619
|
+
// Continues checking all users even after error found
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
return hasError ? { valid: false, error: errorMessage } : { valid: true }
|
|
1623
|
+
}
|
|
1624
|
+
```
|
|
1625
|
+
|
|
1626
|
+
**Correct: returns immediately on first error**
|
|
1627
|
+
|
|
1628
|
+
```typescript
|
|
1629
|
+
function validateUsers(users: User[]) {
|
|
1630
|
+
for (const user of users) {
|
|
1631
|
+
if (!user.email) {
|
|
1632
|
+
return { valid: false, error: 'Email required' }
|
|
1633
|
+
}
|
|
1634
|
+
if (!user.name) {
|
|
1635
|
+
return { valid: false, error: 'Name required' }
|
|
1636
|
+
}
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
return { valid: true }
|
|
1640
|
+
}
|
|
1641
|
+
```
|
|
1642
|
+
|
|
1643
|
+
### 7.9 Hoist RegExp Creation
|
|
1644
|
+
|
|
1645
|
+
Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
|
|
1646
|
+
|
|
1647
|
+
**Incorrect: new RegExp every render**
|
|
1648
|
+
|
|
1649
|
+
```tsx
|
|
1650
|
+
function Highlighter({ text, query }: Props) {
|
|
1651
|
+
const regex = new RegExp(`(${query})`, 'gi')
|
|
1652
|
+
const parts = text.split(regex)
|
|
1653
|
+
return <>{parts.map((part, i) => ...)}</>
|
|
1654
|
+
}
|
|
1655
|
+
```
|
|
1656
|
+
|
|
1657
|
+
**Correct: memoize or hoist**
|
|
1658
|
+
|
|
1659
|
+
```typescript
|
|
1660
|
+
const regex = /foo/g
|
|
1661
|
+
```
|
|
1662
|
+
|
|
1663
|
+
Note: RegExp with global flag (`g`) has stateful `lastIndex`. Cache and reset as needed.
|
|
1664
|
+
|
|
1665
|
+
### 7.10 Use Loop for Min/Max Instead of Sort
|
|
1666
|
+
|
|
1667
|
+
Finding the smallest or largest element only requires a single pass. Sorting is wasteful.
|
|
1668
|
+
|
|
1669
|
+
**Incorrect (O(n log n) - sort to find latest):**
|
|
1670
|
+
|
|
1671
|
+
```typescript
|
|
1672
|
+
interface Project {
|
|
1673
|
+
id: string
|
|
1674
|
+
name: string
|
|
1675
|
+
updatedAt: number
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
function getLatestProject(projects: Project[]) {
|
|
1679
|
+
const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)
|
|
1680
|
+
return sorted[0]
|
|
1681
|
+
}
|
|
1682
|
+
```
|
|
1683
|
+
|
|
1684
|
+
**Correct (O(n) - single loop):**
|
|
1685
|
+
|
|
1686
|
+
```typescript
|
|
1687
|
+
function getLatestProject(projects: Project[]) {
|
|
1688
|
+
if (projects.length === 0) return null
|
|
1689
|
+
|
|
1690
|
+
let latest = projects[0]
|
|
1691
|
+
|
|
1692
|
+
for (let i = 1; i < projects.length; i++) {
|
|
1693
|
+
if (projects[i].updatedAt > latest.updatedAt) {
|
|
1694
|
+
latest = projects[i]
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
|
|
1698
|
+
return latest
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
function getOldestAndNewest(projects: Project[]) {
|
|
1702
|
+
if (projects.length === 0) return { oldest: null, newest: null }
|
|
1703
|
+
|
|
1704
|
+
let oldest = projects[0]
|
|
1705
|
+
let newest = projects[0]
|
|
1706
|
+
|
|
1707
|
+
for (let i = 1; i < projects.length; i++) {
|
|
1708
|
+
if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]
|
|
1709
|
+
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
return { oldest, newest }
|
|
1713
|
+
}
|
|
1714
|
+
```
|
|
1715
|
+
|
|
1716
|
+
Single pass through the array, no copying, no sorting.
|
|
1717
|
+
|
|
1718
|
+
### 7.11 Use Set/Map for O(1) Lookups
|
|
1719
|
+
|
|
1720
|
+
Convert arrays to Set/Map for repeated membership checks.
|
|
1721
|
+
|
|
1722
|
+
**Incorrect (O(n) per check):**
|
|
1723
|
+
|
|
1724
|
+
```typescript
|
|
1725
|
+
const allowedIds = ['a', 'b', 'c', ...]
|
|
1726
|
+
items.filter(item => allowedIds.includes(item.id))
|
|
1727
|
+
```
|
|
1728
|
+
|
|
1729
|
+
**Correct (O(1) per check):**
|
|
1730
|
+
|
|
1731
|
+
```typescript
|
|
1732
|
+
const allowedIds = new Set(['a', 'b', 'c', ...])
|
|
1733
|
+
items.filter(item => allowedIds.has(item.id))
|
|
1734
|
+
```
|
|
1735
|
+
|
|
1736
|
+
### 7.12 Use toSorted() Instead of sort() for Immutability
|
|
1737
|
+
|
|
1738
|
+
`.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.
|
|
1739
|
+
|
|
1740
|
+
**Incorrect: mutates original array**
|
|
1741
|
+
|
|
1742
|
+
```typescript
|
|
1743
|
+
function UserList({ users }: { users: User[] }) {
|
|
1744
|
+
// Mutates the users prop array!
|
|
1745
|
+
const sorted = useMemo(
|
|
1746
|
+
() => users.sort((a, b) => a.name.localeCompare(b.name)),
|
|
1747
|
+
[users]
|
|
1748
|
+
)
|
|
1749
|
+
return <div>{sorted.map(renderUser)}</div>
|
|
1750
|
+
}
|
|
1751
|
+
```
|
|
1752
|
+
|
|
1753
|
+
**Correct: creates new array**
|
|
1754
|
+
|
|
1755
|
+
```typescript
|
|
1756
|
+
function UserList({ users }: { users: User[] }) {
|
|
1757
|
+
// Creates new sorted array, original unchanged
|
|
1758
|
+
const sorted = useMemo(
|
|
1759
|
+
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
|
|
1760
|
+
[users]
|
|
1761
|
+
)
|
|
1762
|
+
return <div>{sorted.map(renderUser)}</div>
|
|
1763
|
+
}
|
|
1764
|
+
```
|
|
1765
|
+
|
|
1766
|
+
**Browser support fallback:**
|
|
1767
|
+
|
|
1768
|
+
```typescript
|
|
1769
|
+
const sorted = [...items].sort((a, b) => a.value - b.value)
|
|
1770
|
+
```
|
|
1771
|
+
|
|
1772
|
+
---
|
|
1773
|
+
|
|
1774
|
+
## 8. Advanced Patterns
|
|
1775
|
+
|
|
1776
|
+
**Impact: LOW**
|
|
1777
|
+
|
|
1778
|
+
Advanced patterns for specific cases that require careful implementation.
|
|
1779
|
+
|
|
1780
|
+
### 8.1 Store Event Handlers in Refs
|
|
1781
|
+
|
|
1782
|
+
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
|
1783
|
+
|
|
1784
|
+
**Incorrect: re-subscribes on every render**
|
|
1785
|
+
|
|
1786
|
+
```tsx
|
|
1787
|
+
function useWindowEvent(event: string, handler: () => void) {
|
|
1788
|
+
useEffect(() => {
|
|
1789
|
+
window.addEventListener(event, handler)
|
|
1790
|
+
return () => window.removeEventListener(event, handler)
|
|
1791
|
+
}, [event, handler])
|
|
1792
|
+
}
|
|
1793
|
+
```
|
|
1794
|
+
|
|
1795
|
+
**Correct: stable subscription**
|
|
1796
|
+
|
|
1797
|
+
```tsx
|
|
1798
|
+
function useWindowEvent(event: string, handler: () => void) {
|
|
1799
|
+
const handlerRef = useRef(handler)
|
|
1800
|
+
useEffect(() => {
|
|
1801
|
+
handlerRef.current = handler
|
|
1802
|
+
}, [handler])
|
|
1803
|
+
|
|
1804
|
+
useEffect(() => {
|
|
1805
|
+
const listener = () => handlerRef.current()
|
|
1806
|
+
window.addEventListener(event, listener)
|
|
1807
|
+
return () => window.removeEventListener(event, listener)
|
|
1808
|
+
}, [event])
|
|
1809
|
+
}
|
|
1810
|
+
```
|
|
1811
|
+
|
|
1812
|
+
### 8.2 useLatest for Stable Callback Refs
|
|
1813
|
+
|
|
1814
|
+
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
|
1815
|
+
|
|
1816
|
+
**Implementation:**
|
|
1817
|
+
|
|
1818
|
+
```typescript
|
|
1819
|
+
function useLatest<T>(value: T) {
|
|
1820
|
+
const ref = useRef(value)
|
|
1821
|
+
useEffect(() => {
|
|
1822
|
+
ref.current = value
|
|
1823
|
+
}, [value])
|
|
1824
|
+
return ref
|
|
1825
|
+
}
|
|
1826
|
+
```
|
|
1827
|
+
|
|
1828
|
+
**Incorrect: effect re-runs on every callback change**
|
|
1829
|
+
|
|
1830
|
+
```tsx
|
|
1831
|
+
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
|
1832
|
+
const [query, setQuery] = useState('')
|
|
1833
|
+
|
|
1834
|
+
useEffect(() => {
|
|
1835
|
+
const timeout = setTimeout(() => onSearch(query), 300)
|
|
1836
|
+
return () => clearTimeout(timeout)
|
|
1837
|
+
}, [query, onSearch])
|
|
1838
|
+
}
|
|
1839
|
+
```
|
|
1840
|
+
|
|
1841
|
+
**Correct: stable effect, fresh callback**
|
|
1842
|
+
|
|
1843
|
+
```tsx
|
|
1844
|
+
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
|
1845
|
+
const [query, setQuery] = useState('')
|
|
1846
|
+
const onSearchRef = useLatest(onSearch)
|
|
1847
|
+
|
|
1848
|
+
useEffect(() => {
|
|
1849
|
+
const timeout = setTimeout(() => onSearchRef.current(query), 300)
|
|
1850
|
+
return () => clearTimeout(timeout)
|
|
1851
|
+
}, [query])
|
|
1852
|
+
}
|
|
1853
|
+
```
|
|
1854
|
+
|
|
1855
|
+
---
|
|
1856
|
+
|
|
1857
|
+
## References
|
|
1858
|
+
|
|
1859
|
+
1. [https://react.dev](https://react.dev)
|
|
1860
|
+
2. [https://nextjs.org](https://nextjs.org)
|
|
1861
|
+
3. [https://swr.vercel.app](https://swr.vercel.app)
|
|
1862
|
+
4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
|
1863
|
+
5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
|
1864
|
+
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)
|
|
1865
|
+
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)
|