agents-config 1.1.0 → 1.1.2

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