@adonis0123/react-best-practices 1.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.
Files changed (55) hide show
  1. package/.claude-skill.json +19 -0
  2. package/AGENTS.md +2249 -0
  3. package/README.md +123 -0
  4. package/SKILL.md +121 -0
  5. package/install-skill.js +207 -0
  6. package/package.json +37 -0
  7. package/rules/_sections.md +46 -0
  8. package/rules/_template.md +28 -0
  9. package/rules/advanced-event-handler-refs.md +55 -0
  10. package/rules/advanced-use-latest.md +49 -0
  11. package/rules/async-api-routes.md +38 -0
  12. package/rules/async-defer-await.md +80 -0
  13. package/rules/async-dependencies.md +36 -0
  14. package/rules/async-parallel.md +28 -0
  15. package/rules/async-suspense-boundaries.md +99 -0
  16. package/rules/bundle-barrel-imports.md +59 -0
  17. package/rules/bundle-conditional.md +31 -0
  18. package/rules/bundle-defer-third-party.md +49 -0
  19. package/rules/bundle-dynamic-imports.md +35 -0
  20. package/rules/bundle-preload.md +50 -0
  21. package/rules/client-event-listeners.md +74 -0
  22. package/rules/client-swr-dedup.md +56 -0
  23. package/rules/js-batch-dom-css.md +82 -0
  24. package/rules/js-cache-function-results.md +80 -0
  25. package/rules/js-cache-property-access.md +28 -0
  26. package/rules/js-cache-storage.md +70 -0
  27. package/rules/js-combine-iterations.md +32 -0
  28. package/rules/js-early-exit.md +50 -0
  29. package/rules/js-hoist-regexp.md +45 -0
  30. package/rules/js-index-maps.md +37 -0
  31. package/rules/js-length-check-first.md +49 -0
  32. package/rules/js-min-max-loop.md +82 -0
  33. package/rules/js-set-map-lookups.md +24 -0
  34. package/rules/js-tosorted-immutable.md +57 -0
  35. package/rules/rendering-activity.md +26 -0
  36. package/rules/rendering-animate-svg-wrapper.md +47 -0
  37. package/rules/rendering-conditional-render.md +40 -0
  38. package/rules/rendering-content-visibility.md +38 -0
  39. package/rules/rendering-hoist-jsx.md +46 -0
  40. package/rules/rendering-hydration-no-flicker.md +82 -0
  41. package/rules/rendering-svg-precision.md +28 -0
  42. package/rules/rerender-defer-reads.md +39 -0
  43. package/rules/rerender-dependencies.md +45 -0
  44. package/rules/rerender-derived-state.md +29 -0
  45. package/rules/rerender-functional-setstate.md +74 -0
  46. package/rules/rerender-lazy-state-init.md +58 -0
  47. package/rules/rerender-memo.md +44 -0
  48. package/rules/rerender-transitions.md +40 -0
  49. package/rules/server-after-nonblocking.md +73 -0
  50. package/rules/server-cache-lru.md +41 -0
  51. package/rules/server-cache-react.md +26 -0
  52. package/rules/server-parallel-fetching.md +79 -0
  53. package/rules/server-serialization.md +38 -0
  54. package/uninstall-skill.js +118 -0
  55. package/utils.js +94 -0
package/README.md ADDED
@@ -0,0 +1,123 @@
1
+ # React Best Practices
2
+
3
+ A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.
4
+
5
+ ## Structure
6
+
7
+ - `rules/` - Individual rule files (one per rule)
8
+ - `_sections.md` - Section metadata (titles, impacts, descriptions)
9
+ - `_template.md` - Template for creating new rules
10
+ - `area-description.md` - Individual rule files
11
+ - `src/` - Build scripts and utilities
12
+ - `metadata.json` - Document metadata (version, organization, abstract)
13
+ - __`AGENTS.md`__ - Compiled output (generated)
14
+ - __`test-cases.json`__ - Test cases for LLM evaluation (generated)
15
+
16
+ ## Getting Started
17
+
18
+ 1. Install dependencies:
19
+ ```bash
20
+ pnpm install
21
+ ```
22
+
23
+ 2. Build AGENTS.md from rules:
24
+ ```bash
25
+ pnpm build
26
+ ```
27
+
28
+ 3. Validate rule files:
29
+ ```bash
30
+ pnpm validate
31
+ ```
32
+
33
+ 4. Extract test cases:
34
+ ```bash
35
+ pnpm extract-tests
36
+ ```
37
+
38
+ ## Creating a New Rule
39
+
40
+ 1. Copy `rules/_template.md` to `rules/area-description.md`
41
+ 2. Choose the appropriate area prefix:
42
+ - `async-` for Eliminating Waterfalls (Section 1)
43
+ - `bundle-` for Bundle Size Optimization (Section 2)
44
+ - `server-` for Server-Side Performance (Section 3)
45
+ - `client-` for Client-Side Data Fetching (Section 4)
46
+ - `rerender-` for Re-render Optimization (Section 5)
47
+ - `rendering-` for Rendering Performance (Section 6)
48
+ - `js-` for JavaScript Performance (Section 7)
49
+ - `advanced-` for Advanced Patterns (Section 8)
50
+ 3. Fill in the frontmatter and content
51
+ 4. Ensure you have clear examples with explanations
52
+ 5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
53
+
54
+ ## Rule File Structure
55
+
56
+ Each rule file should follow this structure:
57
+
58
+ ```markdown
59
+ ---
60
+ title: Rule Title Here
61
+ impact: MEDIUM
62
+ impactDescription: Optional description
63
+ tags: tag1, tag2, tag3
64
+ ---
65
+
66
+ ## Rule Title Here
67
+
68
+ Brief explanation of the rule and why it matters.
69
+
70
+ **Incorrect (description of what's wrong):**
71
+
72
+ ```typescript
73
+ // Bad code example
74
+ ```
75
+
76
+ **Correct (description of what's right):**
77
+
78
+ ```typescript
79
+ // Good code example
80
+ ```
81
+
82
+ Optional explanatory text after examples.
83
+
84
+ Reference: [Link](https://example.com)
85
+
86
+ ## File Naming Convention
87
+
88
+ - Files starting with `_` are special (excluded from build)
89
+ - Rule files: `area-description.md` (e.g., `async-parallel.md`)
90
+ - Section is automatically inferred from filename prefix
91
+ - Rules are sorted alphabetically by title within each section
92
+ - IDs (e.g., 1.1, 1.2) are auto-generated during build
93
+
94
+ ## Impact Levels
95
+
96
+ - `CRITICAL` - Highest priority, major performance gains
97
+ - `HIGH` - Significant performance improvements
98
+ - `MEDIUM-HIGH` - Moderate-high gains
99
+ - `MEDIUM` - Moderate performance improvements
100
+ - `LOW-MEDIUM` - Low-medium gains
101
+ - `LOW` - Incremental improvements
102
+
103
+ ## Scripts
104
+
105
+ - `pnpm build` - Compile rules into AGENTS.md
106
+ - `pnpm validate` - Validate all rule files
107
+ - `pnpm extract-tests` - Extract test cases for LLM evaluation
108
+ - `pnpm dev` - Build and validate
109
+
110
+ ## Contributing
111
+
112
+ When adding or modifying rules:
113
+
114
+ 1. Use the correct filename prefix for your section
115
+ 2. Follow the `_template.md` structure
116
+ 3. Include clear bad/good examples with explanations
117
+ 4. Add appropriate tags
118
+ 5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
119
+ 6. Rules are automatically sorted by title - no need to manage numbers!
120
+
121
+ ## Acknowledgments
122
+
123
+ Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
package/SKILL.md ADDED
@@ -0,0 +1,121 @@
1
+ ---
2
+ name: vercel-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
+ ---
5
+
6
+ # Vercel React Best Practices
7
+
8
+ 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.
9
+
10
+ ## When to Apply
11
+
12
+ Reference these guidelines when:
13
+ - Writing new React components or Next.js pages
14
+ - Implementing data fetching (client or server-side)
15
+ - Reviewing code for performance issues
16
+ - Refactoring existing React/Next.js code
17
+ - Optimizing bundle size or load times
18
+
19
+ ## Rule Categories by Priority
20
+
21
+ | Priority | Category | Impact | Prefix |
22
+ |----------|----------|--------|--------|
23
+ | 1 | Eliminating Waterfalls | CRITICAL | `async-` |
24
+ | 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
25
+ | 3 | Server-Side Performance | HIGH | `server-` |
26
+ | 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
27
+ | 5 | Re-render Optimization | MEDIUM | `rerender-` |
28
+ | 6 | Rendering Performance | MEDIUM | `rendering-` |
29
+ | 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
30
+ | 8 | Advanced Patterns | LOW | `advanced-` |
31
+
32
+ ## Quick Reference
33
+
34
+ ### 1. Eliminating Waterfalls (CRITICAL)
35
+
36
+ - `async-defer-await` - Move await into branches where actually used
37
+ - `async-parallel` - Use Promise.all() for independent operations
38
+ - `async-dependencies` - Use better-all for partial dependencies
39
+ - `async-api-routes` - Start promises early, await late in API routes
40
+ - `async-suspense-boundaries` - Use Suspense to stream content
41
+
42
+ ### 2. Bundle Size Optimization (CRITICAL)
43
+
44
+ - `bundle-barrel-imports` - Import directly, avoid barrel files
45
+ - `bundle-dynamic-imports` - Use next/dynamic for heavy components
46
+ - `bundle-defer-third-party` - Load analytics/logging after hydration
47
+ - `bundle-conditional` - Load modules only when feature is activated
48
+ - `bundle-preload` - Preload on hover/focus for perceived speed
49
+
50
+ ### 3. Server-Side Performance (HIGH)
51
+
52
+ - `server-cache-react` - Use React.cache() for per-request deduplication
53
+ - `server-cache-lru` - Use LRU cache for cross-request caching
54
+ - `server-serialization` - Minimize data passed to client components
55
+ - `server-parallel-fetching` - Restructure components to parallelize fetches
56
+ - `server-after-nonblocking` - Use after() for non-blocking operations
57
+
58
+ ### 4. Client-Side Data Fetching (MEDIUM-HIGH)
59
+
60
+ - `client-swr-dedup` - Use SWR for automatic request deduplication
61
+ - `client-event-listeners` - Deduplicate global event listeners
62
+
63
+ ### 5. Re-render Optimization (MEDIUM)
64
+
65
+ - `rerender-defer-reads` - Don't subscribe to state only used in callbacks
66
+ - `rerender-memo` - Extract expensive work into memoized components
67
+ - `rerender-dependencies` - Use primitive dependencies in effects
68
+ - `rerender-derived-state` - Subscribe to derived booleans, not raw values
69
+ - `rerender-functional-setstate` - Use functional setState for stable callbacks
70
+ - `rerender-lazy-state-init` - Pass function to useState for expensive values
71
+ - `rerender-transitions` - Use startTransition for non-urgent updates
72
+
73
+ ### 6. Rendering Performance (MEDIUM)
74
+
75
+ - `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
76
+ - `rendering-content-visibility` - Use content-visibility for long lists
77
+ - `rendering-hoist-jsx` - Extract static JSX outside components
78
+ - `rendering-svg-precision` - Reduce SVG coordinate precision
79
+ - `rendering-hydration-no-flicker` - Use inline script for client-only data
80
+ - `rendering-activity` - Use Activity component for show/hide
81
+ - `rendering-conditional-render` - Use ternary, not && for conditionals
82
+
83
+ ### 7. JavaScript Performance (LOW-MEDIUM)
84
+
85
+ - `js-batch-dom-css` - Group CSS changes via classes or cssText
86
+ - `js-index-maps` - Build Map for repeated lookups
87
+ - `js-cache-property-access` - Cache object properties in loops
88
+ - `js-cache-function-results` - Cache function results in module-level Map
89
+ - `js-cache-storage` - Cache localStorage/sessionStorage reads
90
+ - `js-combine-iterations` - Combine multiple filter/map into one loop
91
+ - `js-length-check-first` - Check array length before expensive comparison
92
+ - `js-early-exit` - Return early from functions
93
+ - `js-hoist-regexp` - Hoist RegExp creation outside loops
94
+ - `js-min-max-loop` - Use loop for min/max instead of sort
95
+ - `js-set-map-lookups` - Use Set/Map for O(1) lookups
96
+ - `js-tosorted-immutable` - Use toSorted() for immutability
97
+
98
+ ### 8. Advanced Patterns (LOW)
99
+
100
+ - `advanced-event-handler-refs` - Store event handlers in refs
101
+ - `advanced-use-latest` - useLatest for stable callback refs
102
+
103
+ ## How to Use
104
+
105
+ Read individual rule files for detailed explanations and code examples:
106
+
107
+ ```
108
+ rules/async-parallel.md
109
+ rules/bundle-barrel-imports.md
110
+ rules/_sections.md
111
+ ```
112
+
113
+ Each rule file contains:
114
+ - Brief explanation of why it matters
115
+ - Incorrect code example with explanation
116
+ - Correct code example with explanation
117
+ - Additional context and references
118
+
119
+ ## Full Compiled Document
120
+
121
+ For the complete guide with all rules expanded: `AGENTS.md`
@@ -0,0 +1,207 @@
1
+ #!/usr/bin/env node
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const os = require('os');
6
+
7
+ const { getEnabledTargets,extractSkillName, detectInstallLocation } = require('./utils');
8
+
9
+ function installToTarget(target, config) {
10
+ console.log(`\n📦 Installing to ${target.name}...`);
11
+
12
+ // Check if this is a global installation
13
+ const isGlobal = process.env.npm_config_global === 'true';
14
+
15
+ // Determine installation location
16
+ const location = detectInstallLocation(target.paths, isGlobal);
17
+
18
+ // Extract skill name from package name (remove scope prefix)
19
+ const skillName = extractSkillName(config.name);
20
+
21
+ const targetDir = path.join(location.base, skillName);
22
+
23
+ // Alternative path format with full package name (including scope)
24
+ const altTargetDir = path.join(location.base, config.name);
25
+
26
+ console.log(` Type: ${location.type}${isGlobal ? ' (global)' : ' (project)'}`);
27
+ console.log(` Directory: ${targetDir}`);
28
+
29
+ // Clean up alternative path format
30
+ if (fs.existsSync(altTargetDir) && altTargetDir !== targetDir) {
31
+ console.log(` 🧹 Cleaning up alternative path format...`);
32
+ fs.rmSync(altTargetDir, { recursive: true, force: true });
33
+ console.log(` ✓ Removed directory: ${config.name}`);
34
+ }
35
+
36
+ // Create target directory
37
+ if (!fs.existsSync(targetDir)) {
38
+ fs.mkdirSync(targetDir, { recursive: true });
39
+ }
40
+
41
+ // Copy SKILL.md (required)
42
+ const skillMdSource = path.join(__dirname, 'SKILL.md');
43
+ if (!fs.existsSync(skillMdSource)) {
44
+ throw new Error('SKILL.md is required but not found');
45
+ }
46
+ fs.copyFileSync(skillMdSource, path.join(targetDir, 'SKILL.md'));
47
+ console.log(' ✓ Copied SKILL.md');
48
+
49
+ // Copy other files
50
+ if (config.files) {
51
+ Object.entries(config.files).forEach(([source, dest]) => {
52
+ const sourcePath = path.join(__dirname, source);
53
+ if (!fs.existsSync(sourcePath)) {
54
+ console.warn(` ⚠ Warning: ${source} not found, skipping`);
55
+ return;
56
+ }
57
+
58
+ const destPath = path.join(targetDir, dest);
59
+
60
+ if (fs.statSync(sourcePath).isDirectory()) {
61
+ copyDir(sourcePath, destPath);
62
+ console.log(` ✓ Copied directory: ${source}`);
63
+ } else {
64
+ // Ensure target directory exists
65
+ const destDir = path.dirname(destPath);
66
+ if (!fs.existsSync(destDir)) {
67
+ fs.mkdirSync(destDir, { recursive: true });
68
+ }
69
+ fs.copyFileSync(sourcePath, destPath);
70
+ console.log(` ✓ Copied file: ${source}`);
71
+ }
72
+ });
73
+ }
74
+
75
+ // Update manifest
76
+ updateManifest(location.base, config, target.name);
77
+
78
+ // Run postinstall hooks
79
+ if (config.hooks && config.hooks.postinstall) {
80
+ console.log(' 🔧 Running postinstall hook...');
81
+ const { execSync } = require('child_process');
82
+ try {
83
+ execSync(config.hooks.postinstall, {
84
+ cwd: targetDir,
85
+ stdio: 'pipe'
86
+ });
87
+ console.log(' ✓ Postinstall hook completed');
88
+ } catch (error) {
89
+ console.warn(` ⚠ Warning: postinstall hook failed`);
90
+ }
91
+ }
92
+
93
+ console.log(` ✅ Installed to ${target.name}`);
94
+ return targetDir;
95
+ }
96
+
97
+ function installSkill() {
98
+ console.log('🚀 Installing AI Coding Skill...\n');
99
+
100
+ // Read configuration
101
+ const configPath = path.join(__dirname, '.claude-skill.json');
102
+ if (!fs.existsSync(configPath)) {
103
+ throw new Error('.claude-skill.json not found');
104
+ }
105
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
106
+
107
+ // Get enabled targets
108
+ const enabledTargets = getEnabledTargets(config);
109
+
110
+ if (enabledTargets.length === 0) {
111
+ console.warn('⚠ No targets enabled in configuration');
112
+ console.warn('Please enable at least one target in .claude-skill.json');
113
+ return;
114
+ }
115
+
116
+ console.log(`Installing skill "${config.name}" to ${enabledTargets.length} target(s):`);
117
+ enabledTargets.forEach(target => {
118
+ console.log(` • ${target.name}`);
119
+ });
120
+
121
+ // Install to all enabled targets
122
+ const installedPaths = [];
123
+ for (const target of enabledTargets) {
124
+ try {
125
+ const installPath = installToTarget(target, config);
126
+ installedPaths.push({ target: target.name, path: installPath });
127
+ } catch (error) {
128
+ console.error(`\n❌ Failed to install to ${target.name}:`, error.message);
129
+ }
130
+ }
131
+
132
+ // Summary
133
+ console.log('\n' + '='.repeat(60));
134
+ console.log('✅ Installation Complete!');
135
+ console.log('='.repeat(60));
136
+
137
+ if (installedPaths.length > 0) {
138
+ console.log('\nInstalled to:');
139
+ installedPaths.forEach(({ target, path: installPath }) => {
140
+ console.log(` • ${target}: ${installPath}`);
141
+ });
142
+
143
+ console.log('\n📖 Next Steps:');
144
+ console.log(' 1. Restart your AI coding tool(s)');
145
+ console.log(' 2. Ask: "What skills are available?"');
146
+ console.log(' 3. Start using your skill!');
147
+ }
148
+ }
149
+
150
+ function copyDir(src, dest) {
151
+ fs.mkdirSync(dest, { recursive: true });
152
+ const entries = fs.readdirSync(src, { withFileTypes: true });
153
+
154
+ for (let entry of entries) {
155
+ const srcPath = path.join(src, entry.name);
156
+ const destPath = path.join(dest, entry.name);
157
+
158
+ if (entry.isDirectory()) {
159
+ copyDir(srcPath, destPath);
160
+ } else {
161
+ fs.copyFileSync(srcPath, destPath);
162
+ }
163
+ }
164
+ }
165
+
166
+ function updateManifest(skillsDir, config, targetName) {
167
+ const manifestPath = path.join(skillsDir, '.skills-manifest.json');
168
+ let manifest = { skills: {} };
169
+
170
+ if (fs.existsSync(manifestPath)) {
171
+ try {
172
+ manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
173
+ } catch (error) {
174
+ console.warn(' Warning: Could not parse existing manifest, creating new one');
175
+ manifest = { skills: {} };
176
+ }
177
+ }
178
+
179
+ // Extract skill name from package name (remove scope prefix)
180
+ const skillName = config.name.startsWith('@') ?
181
+ config.name.split('/')[1] || config.name :
182
+ config.name;
183
+
184
+ manifest.skills[config.name] = {
185
+ version: config.version,
186
+ installedAt: new Date().toISOString(),
187
+ package: config.package || config.name,
188
+ path: path.join(skillsDir, skillName),
189
+ target: targetName
190
+ };
191
+
192
+ fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
193
+ }
194
+
195
+ // Execute installation
196
+ try {
197
+ installSkill();
198
+ } catch (error) {
199
+ console.error('\n❌ Failed to install skill:', error.message);
200
+ console.error('\nTroubleshooting:');
201
+ console.error('- Ensure .claude-skill.json exists and is valid JSON');
202
+ console.error('- Ensure SKILL.md exists');
203
+ console.error('- Check file permissions for target directories');
204
+ console.error('- Verify at least one target is enabled in .claude-skill.json');
205
+ console.error('- Try running with sudo for global installation (if needed)');
206
+ process.exit(1);
207
+ }
package/package.json ADDED
@@ -0,0 +1,37 @@
1
+ {
2
+ "name": "@adonis0123/react-best-practices",
3
+ "version": "1.0.0",
4
+ "description": "Claude Code Skill - React 和 Next.js 性能优化最佳实践指南,来自 Vercel Engineering",
5
+ "scripts": {
6
+ "postinstall": "node install-skill.js",
7
+ "preuninstall": "node uninstall-skill.js",
8
+ "test": "node install-skill.js && echo 'Installation test completed.'"
9
+ },
10
+ "files": [
11
+ "SKILL.md",
12
+ "AGENTS.md",
13
+ "README.md",
14
+ "rules/",
15
+ "install-skill.js",
16
+ "uninstall-skill.js",
17
+ ".claude-skill.json",
18
+ "utils.js"
19
+ ],
20
+ "keywords": [
21
+ "claude-code",
22
+ "skill",
23
+ "react",
24
+ "nextjs",
25
+ "performance",
26
+ "best-practices",
27
+ "vercel"
28
+ ],
29
+ "author": "adonis",
30
+ "license": "MIT",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/Adonis0123/claude-skills.git",
34
+ "directory": "packages/react-best-practices"
35
+ },
36
+ "homepage": "https://github.com/Adonis0123/claude-skills/tree/main/packages/react-best-practices"
37
+ }
@@ -0,0 +1,46 @@
1
+ # Sections
2
+
3
+ This file defines all sections, their ordering, impact levels, and descriptions.
4
+ The section ID (in parentheses) is the filename prefix used to group rules.
5
+
6
+ ---
7
+
8
+ ## 1. Eliminating Waterfalls (async)
9
+
10
+ **Impact:** CRITICAL
11
+ **Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.
12
+
13
+ ## 2. Bundle Size Optimization (bundle)
14
+
15
+ **Impact:** CRITICAL
16
+ **Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.
17
+
18
+ ## 3. Server-Side Performance (server)
19
+
20
+ **Impact:** HIGH
21
+ **Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.
22
+
23
+ ## 4. Client-Side Data Fetching (client)
24
+
25
+ **Impact:** MEDIUM-HIGH
26
+ **Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.
27
+
28
+ ## 5. Re-render Optimization (rerender)
29
+
30
+ **Impact:** MEDIUM
31
+ **Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.
32
+
33
+ ## 6. Rendering Performance (rendering)
34
+
35
+ **Impact:** MEDIUM
36
+ **Description:** Optimizing the rendering process reduces the work the browser needs to do.
37
+
38
+ ## 7. JavaScript Performance (js)
39
+
40
+ **Impact:** LOW-MEDIUM
41
+ **Description:** Micro-optimizations for hot paths can add up to meaningful improvements.
42
+
43
+ ## 8. Advanced Patterns (advanced)
44
+
45
+ **Impact:** LOW
46
+ **Description:** Advanced patterns for specific cases that require careful implementation.
@@ -0,0 +1,28 @@
1
+ ---
2
+ title: Rule Title Here
3
+ impact: MEDIUM
4
+ impactDescription: Optional description of impact (e.g., "20-50% improvement")
5
+ tags: tag1, tag2
6
+ ---
7
+
8
+ ## Rule Title Here
9
+
10
+ **Impact: MEDIUM (optional impact description)**
11
+
12
+ Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.
13
+
14
+ **Incorrect (description of what's wrong):**
15
+
16
+ ```typescript
17
+ // Bad code example here
18
+ const bad = example()
19
+ ```
20
+
21
+ **Correct (description of what's right):**
22
+
23
+ ```typescript
24
+ // Good code example here
25
+ const good = example()
26
+ ```
27
+
28
+ Reference: [Link to documentation or resource](https://example.com)
@@ -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
+ ```