@kood/claude-code 0.3.11 → 0.3.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +30 -8
- package/package.json +4 -4
- package/templates/.claude/skills/nextjs-react-best-practices/AGENTS.md +663 -0
- package/templates/.claude/skills/nextjs-react-best-practices/SKILL.md +269 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/advanced-event-handler-refs.md +55 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/advanced-use-latest.md +49 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/async-api-routes.md +38 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/async-defer-await.md +80 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/async-dependencies.md +36 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/async-parallel.md +28 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/async-suspense-boundaries.md +99 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/bundle-barrel-imports.md +59 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/bundle-conditional.md +31 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/bundle-defer-third-party.md +49 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/bundle-dynamic-imports.md +35 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/bundle-preload.md +50 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/client-event-listeners.md +74 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/client-swr-dedup.md +56 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-batch-dom-css.md +82 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-cache-function-results.md +80 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-cache-property-access.md +28 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-cache-storage.md +70 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-combine-iterations.md +32 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-early-exit.md +50 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-hoist-regexp.md +45 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-index-maps.md +37 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-length-check-first.md +49 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-min-max-loop.md +82 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-set-map-lookups.md +24 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/js-tosorted-immutable.md +57 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-activity.md +26 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-conditional-render.md +40 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-content-visibility.md +38 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-hydration-no-flicker.md +82 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rendering-svg-precision.md +28 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-defer-reads.md +39 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-dependencies.md +45 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-derived-state.md +29 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-functional-setstate.md +74 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-memo.md +44 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/rerender-transitions.md +40 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/server-after-nonblocking.md +73 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/server-cache-lru.md +41 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/server-cache-react.md +26 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/server-parallel-fetching.md +79 -0
- package/templates/.claude/skills/nextjs-react-best-practices/rules/server-serialization.md +38 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/AGENTS.md +751 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/SKILL.md +431 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/async-defer-await.md +80 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/async-dependencies.md +36 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/async-loader.md +44 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/async-parallel.md +28 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/bundle-barrel-imports.md +59 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/bundle-conditional.md +31 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/bundle-defer-third-party.md +49 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/bundle-lazy-routes.md +67 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/bundle-preload.md +50 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/client-event-listeners.md +74 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/client-tanstack-query.md +77 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-batch-dom-css.md +82 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-cache-function-results.md +80 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-cache-property-access.md +28 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-cache-storage.md +70 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-combine-iterations.md +32 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-early-exit.md +50 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-hoist-regexp.md +45 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-index-maps.md +37 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-length-check-first.md +49 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-min-max-loop.md +82 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-set-map-lookups.md +24 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/js-tosorted-immutable.md +57 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rendering-animate-svg-wrapper.md +47 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rendering-conditional-render.md +40 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rendering-content-visibility.md +38 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rendering-hoist-jsx.md +46 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rendering-svg-precision.md +28 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-defer-reads.md +39 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-dependencies.md +45 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-derived-state.md +29 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-functional-setstate.md +74 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-lazy-state-init.md +58 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-memo.md +44 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/rerender-transitions.md +40 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/server-cache-lru.md +41 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/server-deferred-data.md +67 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/server-parallel-fetching.md +60 -0
- package/templates/.claude/skills/tanstack-start-react-best-practices/rules/server-serialization.md +38 -0
- package/templates/.claude/skills/vs-design-diverge/SKILL.md +307 -0
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: nextjs-react-best-practices
|
|
3
|
+
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
|
|
4
|
+
license: MIT
|
|
5
|
+
metadata:
|
|
6
|
+
author: vercel
|
|
7
|
+
version: "1.0.0"
|
|
8
|
+
---
|
|
9
|
+
|
|
10
|
+
# Next.js React Best Practices
|
|
11
|
+
|
|
12
|
+
Comprehensive performance optimization guide for React and Next.js applications maintained by Vercel. Contains 45 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
<communication>
|
|
17
|
+
|
|
18
|
+
## User Communication
|
|
19
|
+
|
|
20
|
+
**IMPORTANT: Always communicate with the user in Korean (한국어), even though this document is in English.**
|
|
21
|
+
|
|
22
|
+
When:
|
|
23
|
+
- Asking questions
|
|
24
|
+
- Providing summaries
|
|
25
|
+
- Explaining decisions
|
|
26
|
+
- Reporting progress
|
|
27
|
+
|
|
28
|
+
Use Korean for all user-facing communication while applying these English guidelines internally.
|
|
29
|
+
|
|
30
|
+
</communication>
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
<when_to_use>
|
|
35
|
+
|
|
36
|
+
## When to Apply
|
|
37
|
+
|
|
38
|
+
| Situation | Description |
|
|
39
|
+
|-----------|-------------|
|
|
40
|
+
| **Writing Components** | Creating new React components or Next.js pages |
|
|
41
|
+
| **Data Fetching** | Implementing client-side or server-side data fetching |
|
|
42
|
+
| **Code Review** | Reviewing code for performance issues |
|
|
43
|
+
| **Refactoring** | Improving existing React/Next.js code |
|
|
44
|
+
| **Optimization** | Optimizing bundle size or load times |
|
|
45
|
+
|
|
46
|
+
</when_to_use>
|
|
47
|
+
|
|
48
|
+
---
|
|
49
|
+
|
|
50
|
+
<categories>
|
|
51
|
+
|
|
52
|
+
## Rule Categories by Priority
|
|
53
|
+
|
|
54
|
+
| Priority | Category | Impact | Prefix |
|
|
55
|
+
|----------|----------|--------|--------|
|
|
56
|
+
| 1 | Eliminating Waterfalls | **CRITICAL** | `async-` |
|
|
57
|
+
| 2 | Bundle Size Optimization | **CRITICAL** | `bundle-` |
|
|
58
|
+
| 3 | Server-Side Performance | HIGH | `server-` |
|
|
59
|
+
| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
|
|
60
|
+
| 5 | Re-render Optimization | MEDIUM | `rerender-` |
|
|
61
|
+
| 6 | Rendering Performance | MEDIUM | `rendering-` |
|
|
62
|
+
| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
|
|
63
|
+
| 8 | Advanced Patterns | LOW | `advanced-` |
|
|
64
|
+
|
|
65
|
+
</categories>
|
|
66
|
+
|
|
67
|
+
---
|
|
68
|
+
|
|
69
|
+
<rules>
|
|
70
|
+
|
|
71
|
+
## Quick Reference
|
|
72
|
+
|
|
73
|
+
### 1. Eliminating Waterfalls (CRITICAL)
|
|
74
|
+
|
|
75
|
+
| Rule | Description |
|
|
76
|
+
|------|-------------|
|
|
77
|
+
| `async-defer-await` | Move await into branches where actually used |
|
|
78
|
+
| `async-parallel` | Use Promise.all() for independent operations |
|
|
79
|
+
| `async-dependencies` | Use better-all for partial dependencies |
|
|
80
|
+
| `async-api-routes` | Start promises early, await late in API routes |
|
|
81
|
+
| `async-suspense-boundaries` | Use Suspense to stream content |
|
|
82
|
+
|
|
83
|
+
### 2. Bundle Size Optimization (CRITICAL)
|
|
84
|
+
|
|
85
|
+
| Rule | Description |
|
|
86
|
+
|------|-------------|
|
|
87
|
+
| `bundle-barrel-imports` | Import directly, avoid barrel files |
|
|
88
|
+
| `bundle-dynamic-imports` | Use next/dynamic for heavy components |
|
|
89
|
+
| `bundle-defer-third-party` | Load analytics/logging after hydration |
|
|
90
|
+
| `bundle-conditional` | Load modules only when feature is activated |
|
|
91
|
+
| `bundle-preload` | Preload on hover/focus for perceived speed |
|
|
92
|
+
|
|
93
|
+
### 3. Server-Side Performance (HIGH)
|
|
94
|
+
|
|
95
|
+
| Rule | Description |
|
|
96
|
+
|------|-------------|
|
|
97
|
+
| `server-cache-react` | Use React.cache() for per-request deduplication |
|
|
98
|
+
| `server-cache-lru` | Use LRU cache for cross-request caching |
|
|
99
|
+
| `server-serialization` | Minimize data passed to client components |
|
|
100
|
+
| `server-parallel-fetching` | Restructure components to parallelize fetches |
|
|
101
|
+
| `server-after-nonblocking` | Use after() for non-blocking operations |
|
|
102
|
+
|
|
103
|
+
### 4. Client-Side Data Fetching (MEDIUM-HIGH)
|
|
104
|
+
|
|
105
|
+
| Rule | Description |
|
|
106
|
+
|------|-------------|
|
|
107
|
+
| `client-swr-dedup` | Use SWR for automatic request deduplication |
|
|
108
|
+
| `client-event-listeners` | Deduplicate global event listeners |
|
|
109
|
+
|
|
110
|
+
### 5. Re-render Optimization (MEDIUM)
|
|
111
|
+
|
|
112
|
+
| Rule | Description |
|
|
113
|
+
|------|-------------|
|
|
114
|
+
| `rerender-defer-reads` | Don't subscribe to state only used in callbacks |
|
|
115
|
+
| `rerender-memo` | Extract expensive work into memoized components |
|
|
116
|
+
| `rerender-dependencies` | Use primitive dependencies in effects |
|
|
117
|
+
| `rerender-derived-state` | Subscribe to derived booleans, not raw values |
|
|
118
|
+
| `rerender-functional-setstate` | Use functional setState for stable callbacks |
|
|
119
|
+
| `rerender-lazy-state-init` | Pass function to useState for expensive values |
|
|
120
|
+
| `rerender-transitions` | Use startTransition for non-urgent updates |
|
|
121
|
+
|
|
122
|
+
### 6. Rendering Performance (MEDIUM)
|
|
123
|
+
|
|
124
|
+
| Rule | Description |
|
|
125
|
+
|------|-------------|
|
|
126
|
+
| `rendering-animate-svg-wrapper` | Animate div wrapper, not SVG element |
|
|
127
|
+
| `rendering-content-visibility` | Use content-visibility for long lists |
|
|
128
|
+
| `rendering-hoist-jsx` | Extract static JSX outside components |
|
|
129
|
+
| `rendering-svg-precision` | Reduce SVG coordinate precision |
|
|
130
|
+
| `rendering-hydration-no-flicker` | Use inline script for client-only data |
|
|
131
|
+
| `rendering-activity` | Use Activity component for show/hide |
|
|
132
|
+
| `rendering-conditional-render` | Use ternary, not && for conditionals |
|
|
133
|
+
|
|
134
|
+
### 7. JavaScript Performance (LOW-MEDIUM)
|
|
135
|
+
|
|
136
|
+
| Rule | Description |
|
|
137
|
+
|------|-------------|
|
|
138
|
+
| `js-batch-dom-css` | Group CSS changes via classes or cssText |
|
|
139
|
+
| `js-index-maps` | Build Map for repeated lookups |
|
|
140
|
+
| `js-cache-property-access` | Cache object properties in loops |
|
|
141
|
+
| `js-cache-function-results` | Cache function results in module-level Map |
|
|
142
|
+
| `js-cache-storage` | Cache localStorage/sessionStorage reads |
|
|
143
|
+
| `js-combine-iterations` | Combine multiple filter/map into one loop |
|
|
144
|
+
| `js-length-check-first` | Check array length before expensive comparison |
|
|
145
|
+
| `js-early-exit` | Return early from functions |
|
|
146
|
+
| `js-hoist-regexp` | Hoist RegExp creation outside loops |
|
|
147
|
+
| `js-min-max-loop` | Use loop for min/max instead of sort |
|
|
148
|
+
| `js-set-map-lookups` | Use Set/Map for O(1) lookups |
|
|
149
|
+
| `js-tosorted-immutable` | Use toSorted() for immutability |
|
|
150
|
+
|
|
151
|
+
### 8. Advanced Patterns (LOW)
|
|
152
|
+
|
|
153
|
+
| Rule | Description |
|
|
154
|
+
|------|-------------|
|
|
155
|
+
| `advanced-event-handler-refs` | Store event handlers in refs |
|
|
156
|
+
| `advanced-use-latest` | useLatest for stable callback refs |
|
|
157
|
+
|
|
158
|
+
</rules>
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
<patterns>
|
|
163
|
+
|
|
164
|
+
## Core Patterns
|
|
165
|
+
|
|
166
|
+
### ✅ Eliminate Waterfalls
|
|
167
|
+
|
|
168
|
+
```typescript
|
|
169
|
+
// ❌ Sequential execution, 3 round trips
|
|
170
|
+
const user = await fetchUser()
|
|
171
|
+
const posts = await fetchPosts()
|
|
172
|
+
const comments = await fetchComments()
|
|
173
|
+
|
|
174
|
+
// ✅ Parallel execution, 1 round trip
|
|
175
|
+
const [user, posts, comments] = await Promise.all([
|
|
176
|
+
fetchUser(),
|
|
177
|
+
fetchPosts(),
|
|
178
|
+
fetchComments()
|
|
179
|
+
])
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
### ✅ Bundle Optimization
|
|
183
|
+
|
|
184
|
+
```tsx
|
|
185
|
+
// ❌ Import entire library (1583 modules, ~2.8s)
|
|
186
|
+
import { Check, X, Menu } from 'lucide-react'
|
|
187
|
+
|
|
188
|
+
// ✅ Direct imports (3 modules only)
|
|
189
|
+
import Check from 'lucide-react/dist/esm/icons/check'
|
|
190
|
+
import X from 'lucide-react/dist/esm/icons/x'
|
|
191
|
+
import Menu from 'lucide-react/dist/esm/icons/menu'
|
|
192
|
+
|
|
193
|
+
// ✅ Next.js 13.5+ auto-optimization
|
|
194
|
+
// next.config.js
|
|
195
|
+
module.exports = {
|
|
196
|
+
experimental: {
|
|
197
|
+
optimizePackageImports: ['lucide-react']
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### ✅ Server Caching
|
|
203
|
+
|
|
204
|
+
```typescript
|
|
205
|
+
import { cache } from 'react'
|
|
206
|
+
|
|
207
|
+
// Per-request deduplication
|
|
208
|
+
export const getCurrentUser = cache(async () => {
|
|
209
|
+
const session = await auth()
|
|
210
|
+
if (!session?.user?.id) return null
|
|
211
|
+
return await db.user.findUnique({ where: { id: session.user.id } })
|
|
212
|
+
})
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
### ✅ Re-render Optimization
|
|
216
|
+
|
|
217
|
+
```tsx
|
|
218
|
+
// ❌ items as dependency, recreated every time
|
|
219
|
+
const addItems = useCallback((newItems: Item[]) => {
|
|
220
|
+
setItems([...items, ...newItems])
|
|
221
|
+
}, [items])
|
|
222
|
+
|
|
223
|
+
// ✅ Stable callback, never recreated
|
|
224
|
+
const addItems = useCallback((newItems: Item[]) => {
|
|
225
|
+
setItems(curr => [...curr, ...newItems])
|
|
226
|
+
}, [])
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
</patterns>
|
|
230
|
+
|
|
231
|
+
---
|
|
232
|
+
|
|
233
|
+
<usage>
|
|
234
|
+
|
|
235
|
+
## Usage
|
|
236
|
+
|
|
237
|
+
**Detailed rules and examples:**
|
|
238
|
+
|
|
239
|
+
```
|
|
240
|
+
rules/async-parallel.md
|
|
241
|
+
rules/bundle-barrel-imports.md
|
|
242
|
+
rules/_sections.md
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
Each rule file contains:
|
|
246
|
+
- ❌ Incorrect code example with explanation
|
|
247
|
+
- ✅ Correct code example with explanation
|
|
248
|
+
- Additional context and references
|
|
249
|
+
- Why it matters
|
|
250
|
+
|
|
251
|
+
**Full compiled document:** `AGENTS.md`
|
|
252
|
+
|
|
253
|
+
</usage>
|
|
254
|
+
|
|
255
|
+
---
|
|
256
|
+
|
|
257
|
+
<references>
|
|
258
|
+
|
|
259
|
+
## References
|
|
260
|
+
|
|
261
|
+
1. [React](https://react.dev)
|
|
262
|
+
2. [Next.js](https://nextjs.org)
|
|
263
|
+
3. [SWR](https://swr.vercel.app)
|
|
264
|
+
4. [better-all](https://github.com/shuding/better-all)
|
|
265
|
+
5. [node-lru-cache](https://github.com/isaacs/node-lru-cache)
|
|
266
|
+
6. [Next.js Package Import Optimization](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
|
|
267
|
+
7. [How We Made the Vercel Dashboard Twice as Fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
|
|
268
|
+
|
|
269
|
+
</references>
|
package/templates/.claude/skills/nextjs-react-best-practices/rules/advanced-event-handler-refs.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Store Event Handlers in Refs
|
|
3
|
+
impact: LOW
|
|
4
|
+
impactDescription: stable subscriptions
|
|
5
|
+
tags: advanced, hooks, refs, event-handlers, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Store Event Handlers in Refs
|
|
9
|
+
|
|
10
|
+
Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.
|
|
11
|
+
|
|
12
|
+
**Incorrect (re-subscribes on every render):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
function useWindowEvent(event: string, handler: () => void) {
|
|
16
|
+
useEffect(() => {
|
|
17
|
+
window.addEventListener(event, handler)
|
|
18
|
+
return () => window.removeEventListener(event, handler)
|
|
19
|
+
}, [event, handler])
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
**Correct (stable subscription):**
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
function useWindowEvent(event: string, handler: () => void) {
|
|
27
|
+
const handlerRef = useRef(handler)
|
|
28
|
+
useEffect(() => {
|
|
29
|
+
handlerRef.current = handler
|
|
30
|
+
}, [handler])
|
|
31
|
+
|
|
32
|
+
useEffect(() => {
|
|
33
|
+
const listener = () => handlerRef.current()
|
|
34
|
+
window.addEventListener(event, listener)
|
|
35
|
+
return () => window.removeEventListener(event, listener)
|
|
36
|
+
}, [event])
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
**Alternative: use `useEffectEvent` if you're on latest React:**
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { useEffectEvent } from 'react'
|
|
44
|
+
|
|
45
|
+
function useWindowEvent(event: string, handler: () => void) {
|
|
46
|
+
const onEvent = useEffectEvent(handler)
|
|
47
|
+
|
|
48
|
+
useEffect(() => {
|
|
49
|
+
window.addEventListener(event, onEvent)
|
|
50
|
+
return () => window.removeEventListener(event, onEvent)
|
|
51
|
+
}, [event])
|
|
52
|
+
}
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: useLatest for Stable Callback Refs
|
|
3
|
+
impact: LOW
|
|
4
|
+
impactDescription: prevents effect re-runs
|
|
5
|
+
tags: advanced, hooks, useLatest, refs, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## useLatest for Stable Callback Refs
|
|
9
|
+
|
|
10
|
+
Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.
|
|
11
|
+
|
|
12
|
+
**Implementation:**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
function useLatest<T>(value: T) {
|
|
16
|
+
const ref = useRef(value)
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
ref.current = value
|
|
19
|
+
}, [value])
|
|
20
|
+
return ref
|
|
21
|
+
}
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
**Incorrect (effect re-runs on every callback change):**
|
|
25
|
+
|
|
26
|
+
```tsx
|
|
27
|
+
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
|
28
|
+
const [query, setQuery] = useState('')
|
|
29
|
+
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
const timeout = setTimeout(() => onSearch(query), 300)
|
|
32
|
+
return () => clearTimeout(timeout)
|
|
33
|
+
}, [query, onSearch])
|
|
34
|
+
}
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**Correct (stable effect, fresh callback):**
|
|
38
|
+
|
|
39
|
+
```tsx
|
|
40
|
+
function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
|
|
41
|
+
const [query, setQuery] = useState('')
|
|
42
|
+
const onSearchRef = useLatest(onSearch)
|
|
43
|
+
|
|
44
|
+
useEffect(() => {
|
|
45
|
+
const timeout = setTimeout(() => onSearchRef.current(query), 300)
|
|
46
|
+
return () => clearTimeout(timeout)
|
|
47
|
+
}, [query])
|
|
48
|
+
}
|
|
49
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Prevent Waterfall Chains in API Routes
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: 2-10× improvement
|
|
5
|
+
tags: api-routes, server-actions, waterfalls, parallelization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Prevent Waterfall Chains in API Routes
|
|
9
|
+
|
|
10
|
+
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
|
11
|
+
|
|
12
|
+
**Incorrect (config waits for auth, data waits for both):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
export async function GET(request: Request) {
|
|
16
|
+
const session = await auth()
|
|
17
|
+
const config = await fetchConfig()
|
|
18
|
+
const data = await fetchData(session.user.id)
|
|
19
|
+
return Response.json({ data, config })
|
|
20
|
+
}
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
**Correct (auth and config start immediately):**
|
|
24
|
+
|
|
25
|
+
```typescript
|
|
26
|
+
export async function GET(request: Request) {
|
|
27
|
+
const sessionPromise = auth()
|
|
28
|
+
const configPromise = fetchConfig()
|
|
29
|
+
const session = await sessionPromise
|
|
30
|
+
const [config, data] = await Promise.all([
|
|
31
|
+
configPromise,
|
|
32
|
+
fetchData(session.user.id)
|
|
33
|
+
])
|
|
34
|
+
return Response.json({ data, config })
|
|
35
|
+
}
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Defer Await Until Needed
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: avoids blocking unused code paths
|
|
5
|
+
tags: async, await, conditional, optimization
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Defer Await Until Needed
|
|
9
|
+
|
|
10
|
+
Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.
|
|
11
|
+
|
|
12
|
+
**Incorrect (blocks both branches):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
async function handleRequest(userId: string, skipProcessing: boolean) {
|
|
16
|
+
const userData = await fetchUserData(userId)
|
|
17
|
+
|
|
18
|
+
if (skipProcessing) {
|
|
19
|
+
// Returns immediately but still waited for userData
|
|
20
|
+
return { skipped: true }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Only this branch uses userData
|
|
24
|
+
return processUserData(userData)
|
|
25
|
+
}
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
**Correct (only blocks when needed):**
|
|
29
|
+
|
|
30
|
+
```typescript
|
|
31
|
+
async function handleRequest(userId: string, skipProcessing: boolean) {
|
|
32
|
+
if (skipProcessing) {
|
|
33
|
+
// Returns immediately without waiting
|
|
34
|
+
return { skipped: true }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Fetch only when needed
|
|
38
|
+
const userData = await fetchUserData(userId)
|
|
39
|
+
return processUserData(userData)
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
**Another example (early return optimization):**
|
|
44
|
+
|
|
45
|
+
```typescript
|
|
46
|
+
// Incorrect: always fetches permissions
|
|
47
|
+
async function updateResource(resourceId: string, userId: string) {
|
|
48
|
+
const permissions = await fetchPermissions(userId)
|
|
49
|
+
const resource = await getResource(resourceId)
|
|
50
|
+
|
|
51
|
+
if (!resource) {
|
|
52
|
+
return { error: 'Not found' }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!permissions.canEdit) {
|
|
56
|
+
return { error: 'Forbidden' }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
return await updateResourceData(resource, permissions)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Correct: fetches only when needed
|
|
63
|
+
async function updateResource(resourceId: string, userId: string) {
|
|
64
|
+
const resource = await getResource(resourceId)
|
|
65
|
+
|
|
66
|
+
if (!resource) {
|
|
67
|
+
return { error: 'Not found' }
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const permissions = await fetchPermissions(userId)
|
|
71
|
+
|
|
72
|
+
if (!permissions.canEdit) {
|
|
73
|
+
return { error: 'Forbidden' }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return await updateResourceData(resource, permissions)
|
|
77
|
+
}
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Dependency-Based Parallelization
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: 2-10× improvement
|
|
5
|
+
tags: async, parallelization, dependencies, better-all
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Dependency-Based Parallelization
|
|
9
|
+
|
|
10
|
+
For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
|
|
11
|
+
|
|
12
|
+
**Incorrect (profile waits for config unnecessarily):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
const [user, config] = await Promise.all([
|
|
16
|
+
fetchUser(),
|
|
17
|
+
fetchConfig()
|
|
18
|
+
])
|
|
19
|
+
const profile = await fetchProfile(user.id)
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
**Correct (config and profile run in parallel):**
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
import { all } from 'better-all'
|
|
26
|
+
|
|
27
|
+
const { user, config, profile } = await all({
|
|
28
|
+
async user() { return fetchUser() },
|
|
29
|
+
async config() { return fetchConfig() },
|
|
30
|
+
async profile() {
|
|
31
|
+
return fetchProfile((await this.$.user).id)
|
|
32
|
+
}
|
|
33
|
+
})
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Promise.all() for Independent Operations
|
|
3
|
+
impact: CRITICAL
|
|
4
|
+
impactDescription: 2-10× improvement
|
|
5
|
+
tags: async, parallelization, promises, waterfalls
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Promise.all() for Independent Operations
|
|
9
|
+
|
|
10
|
+
When async operations have no interdependencies, execute them concurrently using `Promise.all()`.
|
|
11
|
+
|
|
12
|
+
**Incorrect (sequential execution, 3 round trips):**
|
|
13
|
+
|
|
14
|
+
```typescript
|
|
15
|
+
const user = await fetchUser()
|
|
16
|
+
const posts = await fetchPosts()
|
|
17
|
+
const comments = await fetchComments()
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
**Correct (parallel execution, 1 round trip):**
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
const [user, posts, comments] = await Promise.all([
|
|
24
|
+
fetchUser(),
|
|
25
|
+
fetchPosts(),
|
|
26
|
+
fetchComments()
|
|
27
|
+
])
|
|
28
|
+
```
|
package/templates/.claude/skills/nextjs-react-best-practices/rules/async-suspense-boundaries.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Strategic Suspense Boundaries
|
|
3
|
+
impact: HIGH
|
|
4
|
+
impactDescription: faster initial paint
|
|
5
|
+
tags: async, suspense, streaming, layout-shift
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Strategic Suspense Boundaries
|
|
9
|
+
|
|
10
|
+
Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.
|
|
11
|
+
|
|
12
|
+
**Incorrect (wrapper blocked by data fetching):**
|
|
13
|
+
|
|
14
|
+
```tsx
|
|
15
|
+
async function Page() {
|
|
16
|
+
const data = await fetchData() // Blocks entire page
|
|
17
|
+
|
|
18
|
+
return (
|
|
19
|
+
<div>
|
|
20
|
+
<div>Sidebar</div>
|
|
21
|
+
<div>Header</div>
|
|
22
|
+
<div>
|
|
23
|
+
<DataDisplay data={data} />
|
|
24
|
+
</div>
|
|
25
|
+
<div>Footer</div>
|
|
26
|
+
</div>
|
|
27
|
+
)
|
|
28
|
+
}
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The entire layout waits for data even though only the middle section needs it.
|
|
32
|
+
|
|
33
|
+
**Correct (wrapper shows immediately, data streams in):**
|
|
34
|
+
|
|
35
|
+
```tsx
|
|
36
|
+
function Page() {
|
|
37
|
+
return (
|
|
38
|
+
<div>
|
|
39
|
+
<div>Sidebar</div>
|
|
40
|
+
<div>Header</div>
|
|
41
|
+
<div>
|
|
42
|
+
<Suspense fallback={<Skeleton />}>
|
|
43
|
+
<DataDisplay />
|
|
44
|
+
</Suspense>
|
|
45
|
+
</div>
|
|
46
|
+
<div>Footer</div>
|
|
47
|
+
</div>
|
|
48
|
+
)
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
async function DataDisplay() {
|
|
52
|
+
const data = await fetchData() // Only blocks this component
|
|
53
|
+
return <div>{data.content}</div>
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.
|
|
58
|
+
|
|
59
|
+
**Alternative (share promise across components):**
|
|
60
|
+
|
|
61
|
+
```tsx
|
|
62
|
+
function Page() {
|
|
63
|
+
// Start fetch immediately, but don't await
|
|
64
|
+
const dataPromise = fetchData()
|
|
65
|
+
|
|
66
|
+
return (
|
|
67
|
+
<div>
|
|
68
|
+
<div>Sidebar</div>
|
|
69
|
+
<div>Header</div>
|
|
70
|
+
<Suspense fallback={<Skeleton />}>
|
|
71
|
+
<DataDisplay dataPromise={dataPromise} />
|
|
72
|
+
<DataSummary dataPromise={dataPromise} />
|
|
73
|
+
</Suspense>
|
|
74
|
+
<div>Footer</div>
|
|
75
|
+
</div>
|
|
76
|
+
)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {
|
|
80
|
+
const data = use(dataPromise) // Unwraps the promise
|
|
81
|
+
return <div>{data.content}</div>
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {
|
|
85
|
+
const data = use(dataPromise) // Reuses the same promise
|
|
86
|
+
return <div>{data.summary}</div>
|
|
87
|
+
}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.
|
|
91
|
+
|
|
92
|
+
**When NOT to use this pattern:**
|
|
93
|
+
|
|
94
|
+
- Critical data needed for layout decisions (affects positioning)
|
|
95
|
+
- SEO-critical content above the fold
|
|
96
|
+
- Small, fast queries where suspense overhead isn't worth it
|
|
97
|
+
- When you want to avoid layout shift (loading → content jump)
|
|
98
|
+
|
|
99
|
+
**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.
|