cp-toolkit 2.0.0
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/README.md +130 -0
- package/bin/cp-kit.js +72 -0
- package/package.json +46 -0
- package/src/commands/add.js +212 -0
- package/src/commands/doctor.js +149 -0
- package/src/commands/init.js +662 -0
- package/src/commands/list.js +128 -0
- package/src/index.js +13 -0
- package/templates/agents/backend-specialist.md +263 -0
- package/templates/agents/code-archaeologist.md +106 -0
- package/templates/agents/database-architect.md +226 -0
- package/templates/agents/debugger.md +225 -0
- package/templates/agents/devops-engineer.md +242 -0
- package/templates/agents/documentation-writer.md +104 -0
- package/templates/agents/explorer-agent.md +73 -0
- package/templates/agents/frontend-specialist.md +556 -0
- package/templates/agents/game-developer.md +162 -0
- package/templates/agents/mobile-developer.md +377 -0
- package/templates/agents/orchestrator.md +416 -0
- package/templates/agents/penetration-tester.md +188 -0
- package/templates/agents/performance-optimizer.md +187 -0
- package/templates/agents/product-manager.md +112 -0
- package/templates/agents/product-owner.md +95 -0
- package/templates/agents/project-planner.md +406 -0
- package/templates/agents/qa-automation-engineer.md +103 -0
- package/templates/agents/security-auditor.md +170 -0
- package/templates/agents/seo-specialist.md +111 -0
- package/templates/agents/test-engineer.md +158 -0
- package/templates/github/agents/backend-specialist.md +67 -0
- package/templates/github/agents/code-archaeologist.md +61 -0
- package/templates/github/agents/database-architect.md +73 -0
- package/templates/github/agents/debugger.md +71 -0
- package/templates/github/agents/devops-engineer.md +85 -0
- package/templates/github/agents/documentation-writer.md +107 -0
- package/templates/github/agents/explorer-agent.md +87 -0
- package/templates/github/agents/frontend-specialist.md +54 -0
- package/templates/github/agents/game-developer.md +94 -0
- package/templates/github/agents/mobile-developer.md +75 -0
- package/templates/github/agents/orchestrator.md +48 -0
- package/templates/github/agents/penetration-tester.md +87 -0
- package/templates/github/agents/performance-optimizer.md +70 -0
- package/templates/github/agents/product-manager.md +85 -0
- package/templates/github/agents/product-owner.md +77 -0
- package/templates/github/agents/project-planner.md +83 -0
- package/templates/github/agents/qa-automation-engineer.md +95 -0
- package/templates/github/agents/security-auditor.md +72 -0
- package/templates/github/agents/seo-specialist.md +78 -0
- package/templates/github/agents/test-engineer.md +79 -0
- package/templates/github/instructions/database.instructions.md +74 -0
- package/templates/github/instructions/python.instructions.md +76 -0
- package/templates/github/instructions/security.instructions.md +73 -0
- package/templates/github/instructions/typescript.instructions.md +50 -0
- package/templates/rules/GEMINI.md +273 -0
- package/templates/scripts/mcp-server.js +704 -0
- package/templates/skills/core/behavioral-modes/SKILL.md +242 -0
- package/templates/skills/core/brainstorming/SKILL.md +163 -0
- package/templates/skills/core/brainstorming/dynamic-questioning.md +350 -0
- package/templates/skills/core/clean-code/SKILL.md +201 -0
- package/templates/skills/core/intelligent-routing/SKILL.md +335 -0
- package/templates/skills/core/mcp-builder/SKILL.md +176 -0
- package/templates/skills/core/parallel-agents/SKILL.md +175 -0
- package/templates/skills/core/plan-writing/SKILL.md +152 -0
- package/templates/skills/optional/api-patterns/SKILL.md +81 -0
- package/templates/skills/optional/api-patterns/api-style.md +42 -0
- package/templates/skills/optional/api-patterns/auth.md +24 -0
- package/templates/skills/optional/api-patterns/documentation.md +26 -0
- package/templates/skills/optional/api-patterns/graphql.md +41 -0
- package/templates/skills/optional/api-patterns/rate-limiting.md +31 -0
- package/templates/skills/optional/api-patterns/response.md +37 -0
- package/templates/skills/optional/api-patterns/rest.md +40 -0
- package/templates/skills/optional/api-patterns/scripts/api_validator.py +211 -0
- package/templates/skills/optional/api-patterns/security-testing.md +122 -0
- package/templates/skills/optional/api-patterns/trpc.md +41 -0
- package/templates/skills/optional/api-patterns/versioning.md +22 -0
- package/templates/skills/optional/app-builder/SKILL.md +75 -0
- package/templates/skills/optional/app-builder/agent-coordination.md +71 -0
- package/templates/skills/optional/app-builder/feature-building.md +53 -0
- package/templates/skills/optional/app-builder/project-detection.md +34 -0
- package/templates/skills/optional/app-builder/scaffolding.md +118 -0
- package/templates/skills/optional/app-builder/tech-stack.md +40 -0
- package/templates/skills/optional/app-builder/templates/SKILL.md +39 -0
- package/templates/skills/optional/app-builder/templates/astro-static/TEMPLATE.md +76 -0
- package/templates/skills/optional/app-builder/templates/chrome-extension/TEMPLATE.md +92 -0
- package/templates/skills/optional/app-builder/templates/cli-tool/TEMPLATE.md +88 -0
- package/templates/skills/optional/app-builder/templates/electron-desktop/TEMPLATE.md +88 -0
- package/templates/skills/optional/app-builder/templates/express-api/TEMPLATE.md +83 -0
- package/templates/skills/optional/app-builder/templates/flutter-app/TEMPLATE.md +90 -0
- package/templates/skills/optional/app-builder/templates/monorepo-turborepo/TEMPLATE.md +90 -0
- package/templates/skills/optional/app-builder/templates/nextjs-fullstack/TEMPLATE.md +82 -0
- package/templates/skills/optional/app-builder/templates/nextjs-saas/TEMPLATE.md +100 -0
- package/templates/skills/optional/app-builder/templates/nextjs-static/TEMPLATE.md +106 -0
- package/templates/skills/optional/app-builder/templates/nuxt-app/TEMPLATE.md +101 -0
- package/templates/skills/optional/app-builder/templates/python-fastapi/TEMPLATE.md +83 -0
- package/templates/skills/optional/app-builder/templates/react-native-app/TEMPLATE.md +93 -0
- package/templates/skills/optional/architecture/SKILL.md +55 -0
- package/templates/skills/optional/architecture/context-discovery.md +43 -0
- package/templates/skills/optional/architecture/examples.md +94 -0
- package/templates/skills/optional/architecture/pattern-selection.md +68 -0
- package/templates/skills/optional/architecture/patterns-reference.md +50 -0
- package/templates/skills/optional/architecture/trade-off-analysis.md +77 -0
- package/templates/skills/optional/bash-linux/SKILL.md +199 -0
- package/templates/skills/optional/code-review-checklist/SKILL.md +109 -0
- package/templates/skills/optional/database-design/SKILL.md +52 -0
- package/templates/skills/optional/database-design/database-selection.md +43 -0
- package/templates/skills/optional/database-design/indexing.md +39 -0
- package/templates/skills/optional/database-design/migrations.md +48 -0
- package/templates/skills/optional/database-design/optimization.md +36 -0
- package/templates/skills/optional/database-design/orm-selection.md +30 -0
- package/templates/skills/optional/database-design/schema-design.md +56 -0
- package/templates/skills/optional/database-design/scripts/schema_validator.py +172 -0
- package/templates/skills/optional/deployment-procedures/SKILL.md +241 -0
- package/templates/skills/optional/documentation-templates/SKILL.md +194 -0
- package/templates/skills/optional/frontend-design/SKILL.md +418 -0
- package/templates/skills/optional/frontend-design/animation-guide.md +331 -0
- package/templates/skills/optional/frontend-design/color-system.md +311 -0
- package/templates/skills/optional/frontend-design/decision-trees.md +418 -0
- package/templates/skills/optional/frontend-design/motion-graphics.md +306 -0
- package/templates/skills/optional/frontend-design/scripts/accessibility_checker.py +183 -0
- package/templates/skills/optional/frontend-design/scripts/ux_audit.py +722 -0
- package/templates/skills/optional/frontend-design/typography-system.md +345 -0
- package/templates/skills/optional/frontend-design/ux-psychology.md +541 -0
- package/templates/skills/optional/frontend-design/visual-effects.md +383 -0
- package/templates/skills/optional/game-development/2d-games/SKILL.md +119 -0
- package/templates/skills/optional/game-development/3d-games/SKILL.md +135 -0
- package/templates/skills/optional/game-development/SKILL.md +167 -0
- package/templates/skills/optional/game-development/game-art/SKILL.md +185 -0
- package/templates/skills/optional/game-development/game-audio/SKILL.md +190 -0
- package/templates/skills/optional/game-development/game-design/SKILL.md +129 -0
- package/templates/skills/optional/game-development/mobile-games/SKILL.md +108 -0
- package/templates/skills/optional/game-development/multiplayer/SKILL.md +132 -0
- package/templates/skills/optional/game-development/pc-games/SKILL.md +144 -0
- package/templates/skills/optional/game-development/vr-ar/SKILL.md +123 -0
- package/templates/skills/optional/game-development/web-games/SKILL.md +150 -0
- package/templates/skills/optional/geo-fundamentals/SKILL.md +156 -0
- package/templates/skills/optional/geo-fundamentals/scripts/geo_checker.py +289 -0
- package/templates/skills/optional/i18n-localization/SKILL.md +154 -0
- package/templates/skills/optional/i18n-localization/scripts/i18n_checker.py +241 -0
- package/templates/skills/optional/lint-and-validate/SKILL.md +45 -0
- package/templates/skills/optional/lint-and-validate/scripts/lint_runner.py +172 -0
- package/templates/skills/optional/lint-and-validate/scripts/type_coverage.py +173 -0
- package/templates/skills/optional/mobile-design/SKILL.md +394 -0
- package/templates/skills/optional/mobile-design/decision-trees.md +516 -0
- package/templates/skills/optional/mobile-design/mobile-backend.md +491 -0
- package/templates/skills/optional/mobile-design/mobile-color-system.md +420 -0
- package/templates/skills/optional/mobile-design/mobile-debugging.md +122 -0
- package/templates/skills/optional/mobile-design/mobile-design-thinking.md +357 -0
- package/templates/skills/optional/mobile-design/mobile-navigation.md +458 -0
- package/templates/skills/optional/mobile-design/mobile-performance.md +767 -0
- package/templates/skills/optional/mobile-design/mobile-testing.md +356 -0
- package/templates/skills/optional/mobile-design/mobile-typography.md +433 -0
- package/templates/skills/optional/mobile-design/platform-android.md +666 -0
- package/templates/skills/optional/mobile-design/platform-ios.md +561 -0
- package/templates/skills/optional/mobile-design/scripts/mobile_audit.py +670 -0
- package/templates/skills/optional/mobile-design/touch-psychology.md +537 -0
- package/templates/skills/optional/nextjs-react-expert/1-async-eliminating-waterfalls.md +312 -0
- package/templates/skills/optional/nextjs-react-expert/2-bundle-bundle-size-optimization.md +240 -0
- package/templates/skills/optional/nextjs-react-expert/3-server-server-side-performance.md +490 -0
- package/templates/skills/optional/nextjs-react-expert/4-client-client-side-data-fetching.md +264 -0
- package/templates/skills/optional/nextjs-react-expert/5-rerender-re-render-optimization.md +581 -0
- package/templates/skills/optional/nextjs-react-expert/6-rendering-rendering-performance.md +432 -0
- package/templates/skills/optional/nextjs-react-expert/7-js-javascript-performance.md +684 -0
- package/templates/skills/optional/nextjs-react-expert/8-advanced-advanced-patterns.md +150 -0
- package/templates/skills/optional/nextjs-react-expert/SKILL.md +267 -0
- package/templates/skills/optional/nextjs-react-expert/scripts/convert_rules.py +222 -0
- package/templates/skills/optional/nextjs-react-expert/scripts/react_performance_checker.py +252 -0
- package/templates/skills/optional/nodejs-best-practices/SKILL.md +333 -0
- package/templates/skills/optional/performance-profiling/SKILL.md +143 -0
- package/templates/skills/optional/performance-profiling/scripts/lighthouse_audit.py +76 -0
- package/templates/skills/optional/powershell-windows/SKILL.md +167 -0
- package/templates/skills/optional/python-patterns/SKILL.md +441 -0
- package/templates/skills/optional/red-team-tactics/SKILL.md +199 -0
- package/templates/skills/optional/seo-fundamentals/SKILL.md +129 -0
- package/templates/skills/optional/seo-fundamentals/scripts/seo_checker.py +219 -0
- package/templates/skills/optional/server-management/SKILL.md +161 -0
- package/templates/skills/optional/systematic-debugging/SKILL.md +109 -0
- package/templates/skills/optional/tailwind-patterns/SKILL.md +269 -0
- package/templates/skills/optional/tdd-workflow/SKILL.md +149 -0
- package/templates/skills/optional/testing-patterns/SKILL.md +178 -0
- package/templates/skills/optional/testing-patterns/scripts/test_runner.py +219 -0
- package/templates/skills/optional/vulnerability-scanner/SKILL.md +276 -0
- package/templates/skills/optional/vulnerability-scanner/checklists.md +121 -0
- package/templates/skills/optional/vulnerability-scanner/scripts/security_scan.py +458 -0
- package/templates/skills/optional/web-design-guidelines/SKILL.md +57 -0
- package/templates/skills/optional/webapp-testing/SKILL.md +187 -0
- package/templates/skills/optional/webapp-testing/scripts/playwright_runner.py +173 -0
- package/templates/workflows/brainstorm.md +113 -0
- package/templates/workflows/create.md +59 -0
- package/templates/workflows/debug.md +103 -0
- package/templates/workflows/deploy.md +176 -0
- package/templates/workflows/enhance.md +63 -0
- package/templates/workflows/orchestrate.md +237 -0
- package/templates/workflows/plan.md +89 -0
- package/templates/workflows/preview.md +81 -0
- package/templates/workflows/status.md +86 -0
- package/templates/workflows/test.md +144 -0
- package/templates/workflows/ui-ux-pro-max.md +296 -0
|
@@ -0,0 +1,581 @@
|
|
|
1
|
+
# 5. Re-render Optimization
|
|
2
|
+
|
|
3
|
+
> **Impact:** MEDIUM
|
|
4
|
+
> **Focus:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
## Overview
|
|
9
|
+
|
|
10
|
+
This section contains **12 rules** focused on re-render optimization.
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
## Rule 5.1: Calculate Derived State During Rendering
|
|
15
|
+
|
|
16
|
+
**Impact:** MEDIUM
|
|
17
|
+
**Tags:** rerender, derived-state, useEffect, state
|
|
18
|
+
|
|
19
|
+
## Calculate Derived State During Rendering
|
|
20
|
+
|
|
21
|
+
If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.
|
|
22
|
+
|
|
23
|
+
**Incorrect (redundant state and effect):**
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
function Form() {
|
|
27
|
+
const [firstName, setFirstName] = useState('First')
|
|
28
|
+
const [lastName, setLastName] = useState('Last')
|
|
29
|
+
const [fullName, setFullName] = useState('')
|
|
30
|
+
|
|
31
|
+
useEffect(() => {
|
|
32
|
+
setFullName(firstName + ' ' + lastName)
|
|
33
|
+
}, [firstName, lastName])
|
|
34
|
+
|
|
35
|
+
return <p>{fullName}</p>
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
**Correct (derive during render):**
|
|
40
|
+
|
|
41
|
+
```tsx
|
|
42
|
+
function Form() {
|
|
43
|
+
const [firstName, setFirstName] = useState('First')
|
|
44
|
+
const [lastName, setLastName] = useState('Last')
|
|
45
|
+
const fullName = firstName + ' ' + lastName
|
|
46
|
+
|
|
47
|
+
return <p>{fullName}</p>
|
|
48
|
+
}
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Rule 5.2: Defer State Reads to Usage Point
|
|
56
|
+
|
|
57
|
+
**Impact:** MEDIUM
|
|
58
|
+
**Tags:** rerender, searchParams, localStorage, optimization
|
|
59
|
+
|
|
60
|
+
## Defer State Reads to Usage Point
|
|
61
|
+
|
|
62
|
+
Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.
|
|
63
|
+
|
|
64
|
+
**Incorrect (subscribes to all searchParams changes):**
|
|
65
|
+
|
|
66
|
+
```tsx
|
|
67
|
+
function ShareButton({ chatId }: { chatId: string }) {
|
|
68
|
+
const searchParams = useSearchParams()
|
|
69
|
+
|
|
70
|
+
const handleShare = () => {
|
|
71
|
+
const ref = searchParams.get('ref')
|
|
72
|
+
shareChat(chatId, { ref })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return <button onClick={handleShare}>Share</button>
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
**Correct (reads on demand, no subscription):**
|
|
80
|
+
|
|
81
|
+
```tsx
|
|
82
|
+
function ShareButton({ chatId }: { chatId: string }) {
|
|
83
|
+
const handleShare = () => {
|
|
84
|
+
const params = new URLSearchParams(window.location.search)
|
|
85
|
+
const ref = params.get('ref')
|
|
86
|
+
shareChat(chatId, { ref })
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return <button onClick={handleShare}>Share</button>
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## Rule 5.3: Do not wrap a simple expression with a primitive result type in useMemo
|
|
96
|
+
|
|
97
|
+
**Impact:** LOW-MEDIUM
|
|
98
|
+
**Tags:** rerender, useMemo, optimization
|
|
99
|
+
|
|
100
|
+
## Do not wrap a simple expression with a primitive result type in useMemo
|
|
101
|
+
|
|
102
|
+
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`.
|
|
103
|
+
Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.
|
|
104
|
+
|
|
105
|
+
**Incorrect:**
|
|
106
|
+
|
|
107
|
+
```tsx
|
|
108
|
+
function Header({ user, notifications }: Props) {
|
|
109
|
+
const isLoading = useMemo(() => {
|
|
110
|
+
return user.isLoading || notifications.isLoading
|
|
111
|
+
}, [user.isLoading, notifications.isLoading])
|
|
112
|
+
|
|
113
|
+
if (isLoading) return <Skeleton />
|
|
114
|
+
// return some markup
|
|
115
|
+
}
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
**Correct:**
|
|
119
|
+
|
|
120
|
+
```tsx
|
|
121
|
+
function Header({ user, notifications }: Props) {
|
|
122
|
+
const isLoading = user.isLoading || notifications.isLoading
|
|
123
|
+
|
|
124
|
+
if (isLoading) return <Skeleton />
|
|
125
|
+
// return some markup
|
|
126
|
+
}
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Rule 5.4: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
|
132
|
+
|
|
133
|
+
**Impact:** MEDIUM
|
|
134
|
+
**Tags:** rerender, memo, optimization
|
|
135
|
+
|
|
136
|
+
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
|
|
137
|
+
|
|
138
|
+
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()`.
|
|
139
|
+
|
|
140
|
+
To address this issue, extract the default value into a constant.
|
|
141
|
+
|
|
142
|
+
**Incorrect (`onClick` has different values on every rerender):**
|
|
143
|
+
|
|
144
|
+
```tsx
|
|
145
|
+
const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {
|
|
146
|
+
// ...
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
// Used without optional onClick
|
|
150
|
+
<UserAvatar />
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Correct (stable default value):**
|
|
154
|
+
|
|
155
|
+
```tsx
|
|
156
|
+
const NOOP = () => {};
|
|
157
|
+
|
|
158
|
+
const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {
|
|
159
|
+
// ...
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
// Used without optional onClick
|
|
163
|
+
<UserAvatar />
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## Rule 5.5: Extract to Memoized Components
|
|
169
|
+
|
|
170
|
+
**Impact:** MEDIUM
|
|
171
|
+
**Tags:** rerender, memo, useMemo, optimization
|
|
172
|
+
|
|
173
|
+
## Extract to Memoized Components
|
|
174
|
+
|
|
175
|
+
Extract expensive work into memoized components to enable early returns before computation.
|
|
176
|
+
|
|
177
|
+
**Incorrect (computes avatar even when loading):**
|
|
178
|
+
|
|
179
|
+
```tsx
|
|
180
|
+
function Profile({ user, loading }: Props) {
|
|
181
|
+
const avatar = useMemo(() => {
|
|
182
|
+
const id = computeAvatarId(user)
|
|
183
|
+
return <Avatar id={id} />
|
|
184
|
+
}, [user])
|
|
185
|
+
|
|
186
|
+
if (loading) return <Skeleton />
|
|
187
|
+
return <div>{avatar}</div>
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
**Correct (skips computation when loading):**
|
|
192
|
+
|
|
193
|
+
```tsx
|
|
194
|
+
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
|
|
195
|
+
const id = useMemo(() => computeAvatarId(user), [user])
|
|
196
|
+
return <Avatar id={id} />
|
|
197
|
+
})
|
|
198
|
+
|
|
199
|
+
function Profile({ user, loading }: Props) {
|
|
200
|
+
if (loading) return <Skeleton />
|
|
201
|
+
return (
|
|
202
|
+
<div>
|
|
203
|
+
<UserAvatar user={user} />
|
|
204
|
+
</div>
|
|
205
|
+
)
|
|
206
|
+
}
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
**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.
|
|
210
|
+
|
|
211
|
+
---
|
|
212
|
+
|
|
213
|
+
## Rule 5.6: Narrow Effect Dependencies
|
|
214
|
+
|
|
215
|
+
**Impact:** LOW
|
|
216
|
+
**Tags:** rerender, useEffect, dependencies, optimization
|
|
217
|
+
|
|
218
|
+
## Narrow Effect Dependencies
|
|
219
|
+
|
|
220
|
+
Specify primitive dependencies instead of objects to minimize effect re-runs.
|
|
221
|
+
|
|
222
|
+
**Incorrect (re-runs on any user field change):**
|
|
223
|
+
|
|
224
|
+
```tsx
|
|
225
|
+
useEffect(() => {
|
|
226
|
+
console.log(user.id)
|
|
227
|
+
}, [user])
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Correct (re-runs only when id changes):**
|
|
231
|
+
|
|
232
|
+
```tsx
|
|
233
|
+
useEffect(() => {
|
|
234
|
+
console.log(user.id)
|
|
235
|
+
}, [user.id])
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
**For derived state, compute outside effect:**
|
|
239
|
+
|
|
240
|
+
```tsx
|
|
241
|
+
// Incorrect: runs on width=767, 766, 765...
|
|
242
|
+
useEffect(() => {
|
|
243
|
+
if (width < 768) {
|
|
244
|
+
enableMobileMode()
|
|
245
|
+
}
|
|
246
|
+
}, [width])
|
|
247
|
+
|
|
248
|
+
// Correct: runs only on boolean transition
|
|
249
|
+
const isMobile = width < 768
|
|
250
|
+
useEffect(() => {
|
|
251
|
+
if (isMobile) {
|
|
252
|
+
enableMobileMode()
|
|
253
|
+
}
|
|
254
|
+
}, [isMobile])
|
|
255
|
+
```
|
|
256
|
+
|
|
257
|
+
---
|
|
258
|
+
|
|
259
|
+
## Rule 5.7: Put Interaction Logic in Event Handlers
|
|
260
|
+
|
|
261
|
+
**Impact:** MEDIUM
|
|
262
|
+
**Tags:** rerender, useEffect, events, side-effects, dependencies
|
|
263
|
+
|
|
264
|
+
## Put Interaction Logic in Event Handlers
|
|
265
|
+
|
|
266
|
+
If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.
|
|
267
|
+
|
|
268
|
+
**Incorrect (event modeled as state + effect):**
|
|
269
|
+
|
|
270
|
+
```tsx
|
|
271
|
+
function Form() {
|
|
272
|
+
const [submitted, setSubmitted] = useState(false)
|
|
273
|
+
const theme = useContext(ThemeContext)
|
|
274
|
+
|
|
275
|
+
useEffect(() => {
|
|
276
|
+
if (submitted) {
|
|
277
|
+
post('/api/register')
|
|
278
|
+
showToast('Registered', theme)
|
|
279
|
+
}
|
|
280
|
+
}, [submitted, theme])
|
|
281
|
+
|
|
282
|
+
return <button onClick={() => setSubmitted(true)}>Submit</button>
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
**Correct (do it in the handler):**
|
|
287
|
+
|
|
288
|
+
```tsx
|
|
289
|
+
function Form() {
|
|
290
|
+
const theme = useContext(ThemeContext)
|
|
291
|
+
|
|
292
|
+
function handleSubmit() {
|
|
293
|
+
post('/api/register')
|
|
294
|
+
showToast('Registered', theme)
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return <button onClick={handleSubmit}>Submit</button>
|
|
298
|
+
}
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
|
|
302
|
+
|
|
303
|
+
---
|
|
304
|
+
|
|
305
|
+
## Rule 5.8: Subscribe to Derived State
|
|
306
|
+
|
|
307
|
+
**Impact:** MEDIUM
|
|
308
|
+
**Tags:** rerender, derived-state, media-query, optimization
|
|
309
|
+
|
|
310
|
+
## Subscribe to Derived State
|
|
311
|
+
|
|
312
|
+
Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.
|
|
313
|
+
|
|
314
|
+
**Incorrect (re-renders on every pixel change):**
|
|
315
|
+
|
|
316
|
+
```tsx
|
|
317
|
+
function Sidebar() {
|
|
318
|
+
const width = useWindowWidth() // updates continuously
|
|
319
|
+
const isMobile = width < 768
|
|
320
|
+
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
|
321
|
+
}
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
**Correct (re-renders only when boolean changes):**
|
|
325
|
+
|
|
326
|
+
```tsx
|
|
327
|
+
function Sidebar() {
|
|
328
|
+
const isMobile = useMediaQuery('(max-width: 767px)')
|
|
329
|
+
return <nav className={isMobile ? 'mobile' : 'desktop'} />
|
|
330
|
+
}
|
|
331
|
+
```
|
|
332
|
+
|
|
333
|
+
---
|
|
334
|
+
|
|
335
|
+
## Rule 5.9: Use Functional setState Updates
|
|
336
|
+
|
|
337
|
+
**Impact:** MEDIUM
|
|
338
|
+
**Tags:** react, hooks, useState, useCallback, callbacks, closures
|
|
339
|
+
|
|
340
|
+
## Use Functional setState Updates
|
|
341
|
+
|
|
342
|
+
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.
|
|
343
|
+
|
|
344
|
+
**Incorrect (requires state as dependency):**
|
|
345
|
+
|
|
346
|
+
```tsx
|
|
347
|
+
function TodoList() {
|
|
348
|
+
const [items, setItems] = useState(initialItems)
|
|
349
|
+
|
|
350
|
+
// Callback must depend on items, recreated on every items change
|
|
351
|
+
const addItems = useCallback((newItems: Item[]) => {
|
|
352
|
+
setItems([...items, ...newItems])
|
|
353
|
+
}, [items]) // ❌ items dependency causes recreations
|
|
354
|
+
|
|
355
|
+
// Risk of stale closure if dependency is forgotten
|
|
356
|
+
const removeItem = useCallback((id: string) => {
|
|
357
|
+
setItems(items.filter(item => item.id !== id))
|
|
358
|
+
}, []) // ❌ Missing items dependency - will use stale items!
|
|
359
|
+
|
|
360
|
+
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
|
361
|
+
}
|
|
362
|
+
```
|
|
363
|
+
|
|
364
|
+
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.
|
|
365
|
+
|
|
366
|
+
**Correct (stable callbacks, no stale closures):**
|
|
367
|
+
|
|
368
|
+
```tsx
|
|
369
|
+
function TodoList() {
|
|
370
|
+
const [items, setItems] = useState(initialItems)
|
|
371
|
+
|
|
372
|
+
// Stable callback, never recreated
|
|
373
|
+
const addItems = useCallback((newItems: Item[]) => {
|
|
374
|
+
setItems(curr => [...curr, ...newItems])
|
|
375
|
+
}, []) // ✅ No dependencies needed
|
|
376
|
+
|
|
377
|
+
// Always uses latest state, no stale closure risk
|
|
378
|
+
const removeItem = useCallback((id: string) => {
|
|
379
|
+
setItems(curr => curr.filter(item => item.id !== id))
|
|
380
|
+
}, []) // ✅ Safe and stable
|
|
381
|
+
|
|
382
|
+
return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />
|
|
383
|
+
}
|
|
384
|
+
```
|
|
385
|
+
|
|
386
|
+
**Benefits:**
|
|
387
|
+
|
|
388
|
+
1. **Stable callback references** - Callbacks don't need to be recreated when state changes
|
|
389
|
+
2. **No stale closures** - Always operates on the latest state value
|
|
390
|
+
3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks
|
|
391
|
+
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
|
|
392
|
+
|
|
393
|
+
**When to use functional updates:**
|
|
394
|
+
|
|
395
|
+
- Any setState that depends on the current state value
|
|
396
|
+
- Inside useCallback/useMemo when state is needed
|
|
397
|
+
- Event handlers that reference state
|
|
398
|
+
- Async operations that update state
|
|
399
|
+
|
|
400
|
+
**When direct updates are fine:**
|
|
401
|
+
|
|
402
|
+
- Setting state to a static value: `setCount(0)`
|
|
403
|
+
- Setting state from props/arguments only: `setName(newName)`
|
|
404
|
+
- State doesn't depend on previous value
|
|
405
|
+
|
|
406
|
+
**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.
|
|
407
|
+
|
|
408
|
+
---
|
|
409
|
+
|
|
410
|
+
## Rule 5.10: Use Lazy State Initialization
|
|
411
|
+
|
|
412
|
+
**Impact:** MEDIUM
|
|
413
|
+
**Tags:** react, hooks, useState, performance, initialization
|
|
414
|
+
|
|
415
|
+
## Use Lazy State Initialization
|
|
416
|
+
|
|
417
|
+
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.
|
|
418
|
+
|
|
419
|
+
**Incorrect (runs on every render):**
|
|
420
|
+
|
|
421
|
+
```tsx
|
|
422
|
+
function FilteredList({ items }: { items: Item[] }) {
|
|
423
|
+
// buildSearchIndex() runs on EVERY render, even after initialization
|
|
424
|
+
const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))
|
|
425
|
+
const [query, setQuery] = useState('')
|
|
426
|
+
|
|
427
|
+
// When query changes, buildSearchIndex runs again unnecessarily
|
|
428
|
+
return <SearchResults index={searchIndex} query={query} />
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
function UserProfile() {
|
|
432
|
+
// JSON.parse runs on every render
|
|
433
|
+
const [settings, setSettings] = useState(
|
|
434
|
+
JSON.parse(localStorage.getItem('settings') || '{}')
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
return <SettingsForm settings={settings} onChange={setSettings} />
|
|
438
|
+
}
|
|
439
|
+
```
|
|
440
|
+
|
|
441
|
+
**Correct (runs only once):**
|
|
442
|
+
|
|
443
|
+
```tsx
|
|
444
|
+
function FilteredList({ items }: { items: Item[] }) {
|
|
445
|
+
// buildSearchIndex() runs ONLY on initial render
|
|
446
|
+
const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))
|
|
447
|
+
const [query, setQuery] = useState('')
|
|
448
|
+
|
|
449
|
+
return <SearchResults index={searchIndex} query={query} />
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
function UserProfile() {
|
|
453
|
+
// JSON.parse runs only on initial render
|
|
454
|
+
const [settings, setSettings] = useState(() => {
|
|
455
|
+
const stored = localStorage.getItem('settings')
|
|
456
|
+
return stored ? JSON.parse(stored) : {}
|
|
457
|
+
})
|
|
458
|
+
|
|
459
|
+
return <SettingsForm settings={settings} onChange={setSettings} />
|
|
460
|
+
}
|
|
461
|
+
```
|
|
462
|
+
|
|
463
|
+
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
|
|
464
|
+
|
|
465
|
+
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
|
|
466
|
+
|
|
467
|
+
---
|
|
468
|
+
|
|
469
|
+
## Rule 5.11: Use Transitions for Non-Urgent Updates
|
|
470
|
+
|
|
471
|
+
**Impact:** MEDIUM
|
|
472
|
+
**Tags:** rerender, transitions, startTransition, performance
|
|
473
|
+
|
|
474
|
+
## Use Transitions for Non-Urgent Updates
|
|
475
|
+
|
|
476
|
+
Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.
|
|
477
|
+
|
|
478
|
+
**Incorrect (blocks UI on every scroll):**
|
|
479
|
+
|
|
480
|
+
```tsx
|
|
481
|
+
function ScrollTracker() {
|
|
482
|
+
const [scrollY, setScrollY] = useState(0)
|
|
483
|
+
useEffect(() => {
|
|
484
|
+
const handler = () => setScrollY(window.scrollY)
|
|
485
|
+
window.addEventListener('scroll', handler, { passive: true })
|
|
486
|
+
return () => window.removeEventListener('scroll', handler)
|
|
487
|
+
}, [])
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
**Correct (non-blocking updates):**
|
|
492
|
+
|
|
493
|
+
```tsx
|
|
494
|
+
import { startTransition } from 'react'
|
|
495
|
+
|
|
496
|
+
function ScrollTracker() {
|
|
497
|
+
const [scrollY, setScrollY] = useState(0)
|
|
498
|
+
useEffect(() => {
|
|
499
|
+
const handler = () => {
|
|
500
|
+
startTransition(() => setScrollY(window.scrollY))
|
|
501
|
+
}
|
|
502
|
+
window.addEventListener('scroll', handler, { passive: true })
|
|
503
|
+
return () => window.removeEventListener('scroll', handler)
|
|
504
|
+
}, [])
|
|
505
|
+
}
|
|
506
|
+
```
|
|
507
|
+
|
|
508
|
+
---
|
|
509
|
+
|
|
510
|
+
## Rule 5.12: Use useRef for Transient Values
|
|
511
|
+
|
|
512
|
+
**Impact:** MEDIUM
|
|
513
|
+
**Tags:** rerender, useref, state, performance
|
|
514
|
+
|
|
515
|
+
## Use useRef for Transient Values
|
|
516
|
+
|
|
517
|
+
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
|
|
518
|
+
|
|
519
|
+
**Incorrect (renders every update):**
|
|
520
|
+
|
|
521
|
+
```tsx
|
|
522
|
+
function Tracker() {
|
|
523
|
+
const [lastX, setLastX] = useState(0)
|
|
524
|
+
|
|
525
|
+
useEffect(() => {
|
|
526
|
+
const onMove = (e: MouseEvent) => setLastX(e.clientX)
|
|
527
|
+
window.addEventListener('mousemove', onMove)
|
|
528
|
+
return () => window.removeEventListener('mousemove', onMove)
|
|
529
|
+
}, [])
|
|
530
|
+
|
|
531
|
+
return (
|
|
532
|
+
<div
|
|
533
|
+
style={{
|
|
534
|
+
position: 'fixed',
|
|
535
|
+
top: 0,
|
|
536
|
+
left: lastX,
|
|
537
|
+
width: 8,
|
|
538
|
+
height: 8,
|
|
539
|
+
background: 'black',
|
|
540
|
+
}}
|
|
541
|
+
/>
|
|
542
|
+
)
|
|
543
|
+
}
|
|
544
|
+
```
|
|
545
|
+
|
|
546
|
+
**Correct (no re-render for tracking):**
|
|
547
|
+
|
|
548
|
+
```tsx
|
|
549
|
+
function Tracker() {
|
|
550
|
+
const lastXRef = useRef(0)
|
|
551
|
+
const dotRef = useRef<HTMLDivElement>(null)
|
|
552
|
+
|
|
553
|
+
useEffect(() => {
|
|
554
|
+
const onMove = (e: MouseEvent) => {
|
|
555
|
+
lastXRef.current = e.clientX
|
|
556
|
+
const node = dotRef.current
|
|
557
|
+
if (node) {
|
|
558
|
+
node.style.transform = `translateX(${e.clientX}px)`
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
window.addEventListener('mousemove', onMove)
|
|
562
|
+
return () => window.removeEventListener('mousemove', onMove)
|
|
563
|
+
}, [])
|
|
564
|
+
|
|
565
|
+
return (
|
|
566
|
+
<div
|
|
567
|
+
ref={dotRef}
|
|
568
|
+
style={{
|
|
569
|
+
position: 'fixed',
|
|
570
|
+
top: 0,
|
|
571
|
+
left: 0,
|
|
572
|
+
width: 8,
|
|
573
|
+
height: 8,
|
|
574
|
+
background: 'black',
|
|
575
|
+
transform: 'translateX(0px)',
|
|
576
|
+
}}
|
|
577
|
+
/>
|
|
578
|
+
)
|
|
579
|
+
}
|
|
580
|
+
```
|
|
581
|
+
|