rogasper commited on
Commit
52afa91
·
1 Parent(s): 9205030

chore: remove outdated React best practices documentation and related files. This includes the AGENTS.md, metadata.json, README.md, SKILL.md, and various rule files, streamlining the repository by eliminating unnecessary content.

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .agents/skills/vercel-react-best-practices/AGENTS.md +0 -0
  2. .agents/skills/vercel-react-best-practices/README.md +0 -127
  3. .agents/skills/vercel-react-best-practices/SKILL.md +0 -151
  4. .agents/skills/vercel-react-best-practices/metadata.json +0 -15
  5. .agents/skills/vercel-react-best-practices/rules/_sections.md +0 -46
  6. .agents/skills/vercel-react-best-practices/rules/_template.md +0 -28
  7. .agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md +0 -50
  8. .agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md +0 -55
  9. .agents/skills/vercel-react-best-practices/rules/advanced-init-once.md +0 -42
  10. .agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md +0 -39
  11. .agents/skills/vercel-react-best-practices/rules/async-api-routes.md +0 -35
  12. .agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md +0 -37
  13. .agents/skills/vercel-react-best-practices/rules/async-defer-await.md +0 -82
  14. .agents/skills/vercel-react-best-practices/rules/async-dependencies.md +0 -48
  15. .agents/skills/vercel-react-best-practices/rules/async-parallel.md +0 -24
  16. .agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md +0 -99
  17. .agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md +0 -64
  18. .agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md +0 -60
  19. .agents/skills/vercel-react-best-practices/rules/bundle-conditional.md +0 -37
  20. .agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md +0 -48
  21. .agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md +0 -34
  22. .agents/skills/vercel-react-best-practices/rules/bundle-preload.md +0 -44
  23. .agents/skills/vercel-react-best-practices/rules/client-event-listeners.md +0 -78
  24. .agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md +0 -74
  25. .agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md +0 -48
  26. .agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md +0 -56
  27. .agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md +0 -110
  28. .agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md +0 -80
  29. .agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md +0 -28
  30. .agents/skills/vercel-react-best-practices/rules/js-cache-storage.md +0 -68
  31. .agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md +0 -32
  32. .agents/skills/vercel-react-best-practices/rules/js-early-exit.md +0 -50
  33. .agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md +0 -51
  34. .agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md +0 -45
  35. .agents/skills/vercel-react-best-practices/rules/js-index-maps.md +0 -37
  36. .agents/skills/vercel-react-best-practices/rules/js-length-check-first.md +0 -50
  37. .agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md +0 -82
  38. .agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md +0 -104
  39. .agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md +0 -24
  40. .agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md +0 -57
  41. .agents/skills/vercel-react-best-practices/rules/rendering-activity.md +0 -26
  42. .agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md +0 -38
  43. .agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md +0 -32
  44. .agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md +0 -38
  45. .agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md +0 -36
  46. .agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md +0 -72
  47. .agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md +0 -26
  48. .agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md +0 -85
  49. .agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md +0 -68
  50. .agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md +0 -28
.agents/skills/vercel-react-best-practices/AGENTS.md DELETED
The diff for this file is too large to render. See raw diff
 
.agents/skills/vercel-react-best-practices/README.md DELETED
@@ -1,127 +0,0 @@
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
-
20
- ```bash
21
- pnpm install
22
- ```
23
-
24
- 2. Build AGENTS.md from rules:
25
-
26
- ```bash
27
- pnpm build
28
- ```
29
-
30
- 3. Validate rule files:
31
-
32
- ```bash
33
- pnpm validate
34
- ```
35
-
36
- 4. Extract test cases:
37
- ```bash
38
- pnpm extract-tests
39
- ```
40
-
41
- ## Creating a New Rule
42
-
43
- 1. Copy `rules/_template.md` to `rules/area-description.md`
44
- 2. Choose the appropriate area prefix:
45
- - `async-` for Eliminating Waterfalls (Section 1)
46
- - `bundle-` for Bundle Size Optimization (Section 2)
47
- - `server-` for Server-Side Performance (Section 3)
48
- - `client-` for Client-Side Data Fetching (Section 4)
49
- - `rerender-` for Re-render Optimization (Section 5)
50
- - `rendering-` for Rendering Performance (Section 6)
51
- - `js-` for JavaScript Performance (Section 7)
52
- - `advanced-` for Advanced Patterns (Section 8)
53
- 3. Fill in the frontmatter and content
54
- 4. Ensure you have clear examples with explanations
55
- 5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
56
-
57
- ## Rule File Structure
58
-
59
- Each rule file should follow this structure:
60
-
61
- ````markdown
62
- ---
63
- title: Rule Title Here
64
- impact: MEDIUM
65
- impactDescription: Optional description
66
- tags: tag1, tag2, tag3
67
- ---
68
-
69
- ## Rule Title Here
70
-
71
- Brief explanation of the rule and why it matters.
72
-
73
- **Incorrect (description of what's wrong):**
74
-
75
- ```typescript
76
- // Bad code example
77
- ```
78
- ````
79
-
80
- **Correct (description of what's right):**
81
-
82
- ```typescript
83
- // Good code example
84
- ```
85
-
86
- Optional explanatory text after examples.
87
-
88
- Reference: [Link](https://example.com)
89
-
90
- ## File Naming Convention
91
-
92
- - Files starting with `_` are special (excluded from build)
93
- - Rule files: `area-description.md` (e.g., `async-parallel.md`)
94
- - Section is automatically inferred from filename prefix
95
- - Rules are sorted alphabetically by title within each section
96
- - IDs (e.g., 1.1, 1.2) are auto-generated during build
97
-
98
- ## Impact Levels
99
-
100
- - `CRITICAL` - Highest priority, major performance gains
101
- - `HIGH` - Significant performance improvements
102
- - `MEDIUM-HIGH` - Moderate-high gains
103
- - `MEDIUM` - Moderate performance improvements
104
- - `LOW-MEDIUM` - Low-medium gains
105
- - `LOW` - Incremental improvements
106
-
107
- ## Scripts
108
-
109
- - `pnpm build` - Compile rules into AGENTS.md
110
- - `pnpm validate` - Validate all rule files
111
- - `pnpm extract-tests` - Extract test cases for LLM evaluation
112
- - `pnpm dev` - Build and validate
113
-
114
- ## Contributing
115
-
116
- When adding or modifying rules:
117
-
118
- 1. Use the correct filename prefix for your section
119
- 2. Follow the `_template.md` structure
120
- 3. Include clear bad/good examples with explanations
121
- 4. Add appropriate tags
122
- 5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json
123
- 6. Rules are automatically sorted by title - no need to manage numbers!
124
-
125
- ## Acknowledgments
126
-
127
- Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/SKILL.md DELETED
@@ -1,151 +0,0 @@
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
- license: MIT
5
- metadata:
6
- author: vercel
7
- version: "1.0.0"
8
- ---
9
-
10
- # Vercel React Best Practices
11
-
12
- Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
13
-
14
- ## When to Apply
15
-
16
- Reference these guidelines when:
17
-
18
- - Writing new React components or Next.js pages
19
- - Implementing data fetching (client or server-side)
20
- - Reviewing code for performance issues
21
- - Refactoring existing React/Next.js code
22
- - Optimizing bundle size or load times
23
-
24
- ## Rule Categories by Priority
25
-
26
- | Priority | Category | Impact | Prefix |
27
- | -------- | ------------------------- | ----------- | ------------ |
28
- | 1 | Eliminating Waterfalls | CRITICAL | `async-` |
29
- | 2 | Bundle Size Optimization | CRITICAL | `bundle-` |
30
- | 3 | Server-Side Performance | HIGH | `server-` |
31
- | 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |
32
- | 5 | Re-render Optimization | MEDIUM | `rerender-` |
33
- | 6 | Rendering Performance | MEDIUM | `rendering-` |
34
- | 7 | JavaScript Performance | LOW-MEDIUM | `js-` |
35
- | 8 | Advanced Patterns | LOW | `advanced-` |
36
-
37
- ## Quick Reference
38
-
39
- ### 1. Eliminating Waterfalls (CRITICAL)
40
-
41
- - `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values
42
- - `async-defer-await` - Move await into branches where actually used
43
- - `async-parallel` - Use Promise.all() for independent operations
44
- - `async-dependencies` - Use better-all for partial dependencies
45
- - `async-api-routes` - Start promises early, await late in API routes
46
- - `async-suspense-boundaries` - Use Suspense to stream content
47
-
48
- ### 2. Bundle Size Optimization (CRITICAL)
49
-
50
- - `bundle-barrel-imports` - Import directly, avoid barrel files
51
- - `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces
52
- - `bundle-dynamic-imports` - Use next/dynamic for heavy components
53
- - `bundle-defer-third-party` - Load analytics/logging after hydration
54
- - `bundle-conditional` - Load modules only when feature is activated
55
- - `bundle-preload` - Preload on hover/focus for perceived speed
56
-
57
- ### 3. Server-Side Performance (HIGH)
58
-
59
- - `server-auth-actions` - Authenticate server actions like API routes
60
- - `server-cache-react` - Use React.cache() for per-request deduplication
61
- - `server-cache-lru` - Use LRU cache for cross-request caching
62
- - `server-dedup-props` - Avoid duplicate serialization in RSC props
63
- - `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level
64
- - `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR
65
- - `server-serialization` - Minimize data passed to client components
66
- - `server-parallel-fetching` - Restructure components to parallelize fetches
67
- - `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all
68
- - `server-after-nonblocking` - Use after() for non-blocking operations
69
-
70
- ### 4. Client-Side Data Fetching (MEDIUM-HIGH)
71
-
72
- - `client-swr-dedup` - Use SWR for automatic request deduplication
73
- - `client-event-listeners` - Deduplicate global event listeners
74
- - `client-passive-event-listeners` - Use passive listeners for scroll
75
- - `client-localstorage-schema` - Version and minimize localStorage data
76
-
77
- ### 5. Re-render Optimization (MEDIUM)
78
-
79
- - `rerender-defer-reads` - Don't subscribe to state only used in callbacks
80
- - `rerender-memo` - Extract expensive work into memoized components
81
- - `rerender-memo-with-default-value` - Hoist default non-primitive props
82
- - `rerender-dependencies` - Use primitive dependencies in effects
83
- - `rerender-derived-state` - Subscribe to derived booleans, not raw values
84
- - `rerender-derived-state-no-effect` - Derive state during render, not effects
85
- - `rerender-functional-setstate` - Use functional setState for stable callbacks
86
- - `rerender-lazy-state-init` - Pass function to useState for expensive values
87
- - `rerender-simple-expression-in-memo` - Avoid memo for simple primitives
88
- - `rerender-split-combined-hooks` - Split hooks with independent dependencies
89
- - `rerender-move-effect-to-event` - Put interaction logic in event handlers
90
- - `rerender-transitions` - Use startTransition for non-urgent updates
91
- - `rerender-use-deferred-value` - Defer expensive renders to keep input responsive
92
- - `rerender-use-ref-transient-values` - Use refs for transient frequent values
93
- - `rerender-no-inline-components` - Don't define components inside components
94
-
95
- ### 6. Rendering Performance (MEDIUM)
96
-
97
- - `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element
98
- - `rendering-content-visibility` - Use content-visibility for long lists
99
- - `rendering-hoist-jsx` - Extract static JSX outside components
100
- - `rendering-svg-precision` - Reduce SVG coordinate precision
101
- - `rendering-hydration-no-flicker` - Use inline script for client-only data
102
- - `rendering-hydration-suppress-warning` - Suppress expected mismatches
103
- - `rendering-activity` - Use Activity component for show/hide
104
- - `rendering-conditional-render` - Use ternary, not && for conditionals
105
- - `rendering-usetransition-loading` - Prefer useTransition for loading state
106
- - `rendering-resource-hints` - Use React DOM resource hints for preloading
107
- - `rendering-script-defer-async` - Use defer or async on script tags
108
-
109
- ### 7. JavaScript Performance (LOW-MEDIUM)
110
-
111
- - `js-batch-dom-css` - Group CSS changes via classes or cssText
112
- - `js-index-maps` - Build Map for repeated lookups
113
- - `js-cache-property-access` - Cache object properties in loops
114
- - `js-cache-function-results` - Cache function results in module-level Map
115
- - `js-cache-storage` - Cache localStorage/sessionStorage reads
116
- - `js-combine-iterations` - Combine multiple filter/map into one loop
117
- - `js-length-check-first` - Check array length before expensive comparison
118
- - `js-early-exit` - Return early from functions
119
- - `js-hoist-regexp` - Hoist RegExp creation outside loops
120
- - `js-min-max-loop` - Use loop for min/max instead of sort
121
- - `js-set-map-lookups` - Use Set/Map for O(1) lookups
122
- - `js-tosorted-immutable` - Use toSorted() for immutability
123
- - `js-flatmap-filter` - Use flatMap to map and filter in one pass
124
- - `js-request-idle-callback` - Defer non-critical work to browser idle time
125
-
126
- ### 8. Advanced Patterns (LOW)
127
-
128
- - `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps
129
- - `advanced-event-handler-refs` - Store event handlers in refs
130
- - `advanced-init-once` - Initialize app once per app load
131
- - `advanced-use-latest` - useLatest for stable callback refs
132
-
133
- ## How to Use
134
-
135
- Read individual rule files for detailed explanations and code examples:
136
-
137
- ```
138
- rules/async-parallel.md
139
- rules/bundle-barrel-imports.md
140
- ```
141
-
142
- Each rule file contains:
143
-
144
- - Brief explanation of why it matters
145
- - Incorrect code example with explanation
146
- - Correct code example with explanation
147
- - Additional context and references
148
-
149
- ## Full Compiled Document
150
-
151
- For the complete guide with all rules expanded: `AGENTS.md`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/metadata.json DELETED
@@ -1,15 +0,0 @@
1
- {
2
- "version": "1.0.0",
3
- "organization": "Vercel Engineering",
4
- "date": "January 2026",
5
- "abstract": "Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.",
6
- "references": [
7
- "https://react.dev",
8
- "https://nextjs.org",
9
- "https://swr.vercel.app",
10
- "https://github.com/shuding/better-all",
11
- "https://github.com/isaacs/node-lru-cache",
12
- "https://vercel.com/blog/how-we-optimized-package-imports-in-next-js",
13
- "https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast"
14
- ]
15
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/_sections.md DELETED
@@ -1,46 +0,0 @@
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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/_template.md DELETED
@@ -1,28 +0,0 @@
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md DELETED
@@ -1,50 +0,0 @@
1
- ---
2
- title: Do Not Put Effect Events in Dependency Arrays
3
- impact: LOW
4
- impactDescription: avoids unnecessary effect re-runs and lint errors
5
- tags: advanced, hooks, useEffectEvent, dependencies, effects
6
- ---
7
-
8
- ## Do Not Put Effect Events in Dependency Arrays
9
-
10
- Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
11
-
12
- **Incorrect (Effect Event added as a dependency):**
13
-
14
- ```tsx
15
- import { useEffect, useEffectEvent } from "react";
16
-
17
- function ChatRoom({ roomId, onConnected }: { roomId: string; onConnected: () => void }) {
18
- const handleConnected = useEffectEvent(onConnected);
19
-
20
- useEffect(() => {
21
- const connection = createConnection(roomId);
22
- connection.on("connected", handleConnected);
23
- connection.connect();
24
-
25
- return () => connection.disconnect();
26
- }, [roomId, handleConnected]);
27
- }
28
- ```
29
-
30
- Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.
31
-
32
- **Correct (depend on reactive values, not the Effect Event):**
33
-
34
- ```tsx
35
- import { useEffect, useEffectEvent } from "react";
36
-
37
- function ChatRoom({ roomId, onConnected }: { roomId: string; onConnected: () => void }) {
38
- const handleConnected = useEffectEvent(onConnected);
39
-
40
- useEffect(() => {
41
- const connection = createConnection(roomId);
42
- connection.on("connected", handleConnected);
43
- connection.connect();
44
-
45
- return () => connection.disconnect();
46
- }, [roomId]);
47
- }
48
- ```
49
-
50
- Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md DELETED
@@ -1,55 +0,0 @@
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: (e) => 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: (e) => void) {
27
- const handlerRef = useRef(handler);
28
- useEffect(() => {
29
- handlerRef.current = handler;
30
- }, [handler]);
31
-
32
- useEffect(() => {
33
- const listener = (e) => handlerRef.current(e);
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: (e) => 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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md DELETED
@@ -1,42 +0,0 @@
1
- ---
2
- title: Initialize App Once, Not Per Mount
3
- impact: LOW-MEDIUM
4
- impactDescription: avoids duplicate init in development
5
- tags: initialization, useEffect, app-startup, side-effects
6
- ---
7
-
8
- ## Initialize App Once, Not Per Mount
9
-
10
- Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
11
-
12
- **Incorrect (runs twice in dev, re-runs on remount):**
13
-
14
- ```tsx
15
- function Comp() {
16
- useEffect(() => {
17
- loadFromStorage();
18
- checkAuthToken();
19
- }, []);
20
-
21
- // ...
22
- }
23
- ```
24
-
25
- **Correct (once per app load):**
26
-
27
- ```tsx
28
- let didInit = false;
29
-
30
- function Comp() {
31
- useEffect(() => {
32
- if (didInit) return;
33
- didInit = true;
34
- loadFromStorage();
35
- checkAuthToken();
36
- }, []);
37
-
38
- // ...
39
- }
40
- ```
41
-
42
- Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md DELETED
@@ -1,39 +0,0 @@
1
- ---
2
- title: useEffectEvent for Stable Callback Refs
3
- impact: LOW
4
- impactDescription: prevents effect re-runs
5
- tags: advanced, hooks, useEffectEvent, refs, optimization
6
- ---
7
-
8
- ## useEffectEvent 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
- **Incorrect (effect re-runs on every callback change):**
13
-
14
- ```tsx
15
- function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
16
- const [query, setQuery] = useState("");
17
-
18
- useEffect(() => {
19
- const timeout = setTimeout(() => onSearch(query), 300);
20
- return () => clearTimeout(timeout);
21
- }, [query, onSearch]);
22
- }
23
- ```
24
-
25
- **Correct (using React's useEffectEvent):**
26
-
27
- ```tsx
28
- import { useEffectEvent } from "react";
29
-
30
- function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {
31
- const [query, setQuery] = useState("");
32
- const onSearchEvent = useEffectEvent(onSearch);
33
-
34
- useEffect(() => {
35
- const timeout = setTimeout(() => onSearchEvent(query), 300);
36
- return () => clearTimeout(timeout);
37
- }, [query]);
38
- }
39
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/async-api-routes.md DELETED
@@ -1,35 +0,0 @@
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([configPromise, fetchData(session.user.id)]);
31
- return Response.json({ data, config });
32
- }
33
- ```
34
-
35
- For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md DELETED
@@ -1,37 +0,0 @@
1
- ---
2
- title: Check Cheap Conditions Before Async Flags
3
- impact: HIGH
4
- impactDescription: avoids unnecessary async work when a synchronous guard already fails
5
- tags: async, await, feature-flags, short-circuit, conditional
6
- ---
7
-
8
- ## Check Cheap Conditions Before Async Flags
9
-
10
- When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
11
-
12
- This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
13
-
14
- **Incorrect:**
15
-
16
- ```typescript
17
- const someFlag = await getFlag();
18
-
19
- if (someFlag && someCondition) {
20
- // ...
21
- }
22
- ```
23
-
24
- **Correct:**
25
-
26
- ```typescript
27
- if (someCondition) {
28
- const someFlag = await getFlag();
29
- if (someFlag) {
30
- // ...
31
- }
32
- }
33
- ```
34
-
35
- This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
36
-
37
- Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/async-defer-await.md DELETED
@@ -1,82 +0,0 @@
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.
81
-
82
- For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/async-dependencies.md DELETED
@@ -1,48 +0,0 @@
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([fetchUser(), fetchConfig()]);
16
- const profile = await fetchProfile(user.id);
17
- ```
18
-
19
- **Correct (config and profile run in parallel):**
20
-
21
- ```typescript
22
- import { all } from "better-all";
23
-
24
- const { user, config, profile } = await all({
25
- async user() {
26
- return fetchUser();
27
- },
28
- async config() {
29
- return fetchConfig();
30
- },
31
- async profile() {
32
- return fetchProfile((await this.$.user).id);
33
- },
34
- });
35
- ```
36
-
37
- **Alternative without extra dependencies:**
38
-
39
- We can also create all the promises first, and do `Promise.all()` at the end.
40
-
41
- ```typescript
42
- const userPromise = fetchUser();
43
- const profilePromise = userPromise.then((user) => fetchProfile(user.id));
44
-
45
- const [user, config, profile] = await Promise.all([userPromise, fetchConfig(), profilePromise]);
46
- ```
47
-
48
- Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/async-parallel.md DELETED
@@ -1,24 +0,0 @@
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([fetchUser(), fetchPosts(), fetchComments()]);
24
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md DELETED
@@ -1,99 +0,0 @@
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.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md DELETED
@@ -1,64 +0,0 @@
1
- ---
2
- title: Prefer Statically Analyzable Paths
3
- impact: HIGH
4
- impactDescription: avoids accidental broad bundles and file traces
5
- tags: bundle, nextjs, vite, webpack, rollup, esbuild, path
6
- ---
7
-
8
- ## Prefer Statically Analyzable Paths
9
-
10
- Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
11
-
12
- Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
13
-
14
- When analysis becomes too broad, the cost is real:
15
-
16
- - Larger server bundles
17
- - Slower builds
18
- - Worse cold starts
19
- - More memory use
20
-
21
- ### Import Paths
22
-
23
- **Incorrect (the bundler cannot tell what may be imported):**
24
-
25
- ```ts
26
- const PAGE_MODULES = {
27
- home: "./pages/home",
28
- settings: "./pages/settings",
29
- } as const;
30
-
31
- const Page = await import(PAGE_MODULES[pageName]);
32
- ```
33
-
34
- **Correct (use an explicit map of allowed modules):**
35
-
36
- ```ts
37
- const PAGE_MODULES = {
38
- home: () => import("./pages/home"),
39
- settings: () => import("./pages/settings"),
40
- } as const;
41
-
42
- const Page = await PAGE_MODULES[pageName]();
43
- ```
44
-
45
- ### File-System Paths
46
-
47
- **Incorrect (a 2-value enum still hides the final path from static analysis):**
48
-
49
- ```ts
50
- const baseDir = path.join(process.cwd(), "content/" + contentKind);
51
- ```
52
-
53
- **Correct (make each final path literal at the callsite):**
54
-
55
- ```ts
56
- const baseDir =
57
- kind === ContentKind.Blog
58
- ? path.join(process.cwd(), "content/blog")
59
- : path.join(process.cwd(), "content/docs");
60
- ```
61
-
62
- In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
63
-
64
- Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md DELETED
@@ -1,60 +0,0 @@
1
- ---
2
- title: Avoid Barrel File Imports
3
- impact: CRITICAL
4
- impactDescription: 200-800ms import cost, slow builds
5
- tags: bundle, imports, tree-shaking, barrel-files, performance
6
- ---
7
-
8
- ## Avoid Barrel File Imports
9
-
10
- Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).
11
-
12
- Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.
13
-
14
- **Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.
15
-
16
- **Incorrect (imports entire library):**
17
-
18
- ```tsx
19
- import { Check, X, Menu } from "lucide-react";
20
- // Loads 1,583 modules, takes ~2.8s extra in dev
21
- // Runtime cost: 200-800ms on every cold start
22
-
23
- import { Button, TextField } from "@mui/material";
24
- // Loads 2,225 modules, takes ~4.2s extra in dev
25
- ```
26
-
27
- **Correct - Next.js 13.5+ (recommended):**
28
-
29
- ```js
30
- // next.config.js - automatically optimizes barrel imports at build time
31
- module.exports = {
32
- experimental: {
33
- optimizePackageImports: ["lucide-react", "@mui/material"],
34
- },
35
- };
36
- ```
37
-
38
- ```tsx
39
- // Keep the standard imports - Next.js transforms them to direct imports
40
- import { Check, X, Menu } from "lucide-react";
41
- // Full TypeScript support, no manual path wrangling
42
- ```
43
-
44
- This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
45
-
46
- **Correct - Direct imports (non-Next.js projects):**
47
-
48
- ```tsx
49
- import Button from "@mui/material/Button";
50
- import TextField from "@mui/material/TextField";
51
- // Loads only what you use
52
- ```
53
-
54
- > **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
55
-
56
- These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
57
-
58
- Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.
59
-
60
- Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md DELETED
@@ -1,37 +0,0 @@
1
- ---
2
- title: Conditional Module Loading
3
- impact: HIGH
4
- impactDescription: loads large data only when needed
5
- tags: bundle, conditional-loading, lazy-loading
6
- ---
7
-
8
- ## Conditional Module Loading
9
-
10
- Load large data or modules only when a feature is activated.
11
-
12
- **Example (lazy-load animation frames):**
13
-
14
- ```tsx
15
- function AnimationPlayer({
16
- enabled,
17
- setEnabled,
18
- }: {
19
- enabled: boolean;
20
- setEnabled: React.Dispatch<React.SetStateAction<boolean>>;
21
- }) {
22
- const [frames, setFrames] = useState<Frame[] | null>(null);
23
-
24
- useEffect(() => {
25
- if (enabled && !frames && typeof window !== "undefined") {
26
- import("./animation-frames.js")
27
- .then((mod) => setFrames(mod.frames))
28
- .catch(() => setEnabled(false));
29
- }
30
- }, [enabled, frames, setEnabled]);
31
-
32
- if (!frames) return <Skeleton />;
33
- return <Canvas frames={frames} />;
34
- }
35
- ```
36
-
37
- The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md DELETED
@@ -1,48 +0,0 @@
1
- ---
2
- title: Defer Non-Critical Third-Party Libraries
3
- impact: MEDIUM
4
- impactDescription: loads after hydration
5
- tags: bundle, third-party, analytics, defer
6
- ---
7
-
8
- ## Defer Non-Critical Third-Party Libraries
9
-
10
- Analytics, logging, and error tracking don't block user interaction. Load them after hydration.
11
-
12
- **Incorrect (blocks initial bundle):**
13
-
14
- ```tsx
15
- import { Analytics } from "@vercel/analytics/react";
16
-
17
- export default function RootLayout({ children }) {
18
- return (
19
- <html>
20
- <body>
21
- {children}
22
- <Analytics />
23
- </body>
24
- </html>
25
- );
26
- }
27
- ```
28
-
29
- **Correct (loads after hydration):**
30
-
31
- ```tsx
32
- import dynamic from "next/dynamic";
33
-
34
- const Analytics = dynamic(() => import("@vercel/analytics/react").then((m) => m.Analytics), {
35
- ssr: false,
36
- });
37
-
38
- export default function RootLayout({ children }) {
39
- return (
40
- <html>
41
- <body>
42
- {children}
43
- <Analytics />
44
- </body>
45
- </html>
46
- );
47
- }
48
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md DELETED
@@ -1,34 +0,0 @@
1
- ---
2
- title: Dynamic Imports for Heavy Components
3
- impact: CRITICAL
4
- impactDescription: directly affects TTI and LCP
5
- tags: bundle, dynamic-import, code-splitting, next-dynamic
6
- ---
7
-
8
- ## Dynamic Imports for Heavy Components
9
-
10
- Use `next/dynamic` to lazy-load large components not needed on initial render.
11
-
12
- **Incorrect (Monaco bundles with main chunk ~300KB):**
13
-
14
- ```tsx
15
- import { MonacoEditor } from "./monaco-editor";
16
-
17
- function CodePanel({ code }: { code: string }) {
18
- return <MonacoEditor value={code} />;
19
- }
20
- ```
21
-
22
- **Correct (Monaco loads on demand):**
23
-
24
- ```tsx
25
- import dynamic from "next/dynamic";
26
-
27
- const MonacoEditor = dynamic(() => import("./monaco-editor").then((m) => m.MonacoEditor), {
28
- ssr: false,
29
- });
30
-
31
- function CodePanel({ code }: { code: string }) {
32
- return <MonacoEditor value={code} />;
33
- }
34
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/bundle-preload.md DELETED
@@ -1,44 +0,0 @@
1
- ---
2
- title: Preload Based on User Intent
3
- impact: MEDIUM
4
- impactDescription: reduces perceived latency
5
- tags: bundle, preload, user-intent, hover
6
- ---
7
-
8
- ## Preload Based on User Intent
9
-
10
- Preload heavy bundles before they're needed to reduce perceived latency.
11
-
12
- **Example (preload on hover/focus):**
13
-
14
- ```tsx
15
- function EditorButton({ onClick }: { onClick: () => void }) {
16
- const preload = () => {
17
- if (typeof window !== "undefined") {
18
- void import("./monaco-editor");
19
- }
20
- };
21
-
22
- return (
23
- <button onMouseEnter={preload} onFocus={preload} onClick={onClick}>
24
- Open Editor
25
- </button>
26
- );
27
- }
28
- ```
29
-
30
- **Example (preload when feature flag is enabled):**
31
-
32
- ```tsx
33
- function FlagsProvider({ children, flags }: Props) {
34
- useEffect(() => {
35
- if (flags.editorEnabled && typeof window !== "undefined") {
36
- void import("./monaco-editor").then((mod) => mod.init());
37
- }
38
- }, [flags.editorEnabled]);
39
-
40
- return <FlagsContext.Provider value={flags}>{children}</FlagsContext.Provider>;
41
- }
42
- ```
43
-
44
- The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md DELETED
@@ -1,78 +0,0 @@
1
- ---
2
- title: Deduplicate Global Event Listeners
3
- impact: LOW
4
- impactDescription: single listener for N components
5
- tags: client, swr, event-listeners, subscription
6
- ---
7
-
8
- ## Deduplicate Global Event Listeners
9
-
10
- Use `useSWRSubscription()` to share global event listeners across component instances.
11
-
12
- **Incorrect (N instances = N listeners):**
13
-
14
- ```tsx
15
- function useKeyboardShortcut(key: string, callback: () => void) {
16
- useEffect(() => {
17
- const handler = (e: KeyboardEvent) => {
18
- if (e.metaKey && e.key === key) {
19
- callback();
20
- }
21
- };
22
- window.addEventListener("keydown", handler);
23
- return () => window.removeEventListener("keydown", handler);
24
- }, [key, callback]);
25
- }
26
- ```
27
-
28
- When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.
29
-
30
- **Correct (N instances = 1 listener):**
31
-
32
- ```tsx
33
- import useSWRSubscription from "swr/subscription";
34
-
35
- // Module-level Map to track callbacks per key
36
- const keyCallbacks = new Map<string, Set<() => void>>();
37
-
38
- function useKeyboardShortcut(key: string, callback: () => void) {
39
- // Register this callback in the Map
40
- useEffect(() => {
41
- if (!keyCallbacks.has(key)) {
42
- keyCallbacks.set(key, new Set());
43
- }
44
- keyCallbacks.get(key)!.add(callback);
45
-
46
- return () => {
47
- const set = keyCallbacks.get(key);
48
- if (set) {
49
- set.delete(callback);
50
- if (set.size === 0) {
51
- keyCallbacks.delete(key);
52
- }
53
- }
54
- };
55
- }, [key, callback]);
56
-
57
- useSWRSubscription("global-keydown", () => {
58
- const handler = (e: KeyboardEvent) => {
59
- if (e.metaKey && keyCallbacks.has(e.key)) {
60
- keyCallbacks.get(e.key)!.forEach((cb) => cb());
61
- }
62
- };
63
- window.addEventListener("keydown", handler);
64
- return () => window.removeEventListener("keydown", handler);
65
- });
66
- }
67
-
68
- function Profile() {
69
- // Multiple shortcuts will share the same listener
70
- useKeyboardShortcut("p", () => {
71
- /* ... */
72
- });
73
- useKeyboardShortcut("k", () => {
74
- /* ... */
75
- });
76
- // ...
77
- }
78
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md DELETED
@@ -1,74 +0,0 @@
1
- ---
2
- title: Version and Minimize localStorage Data
3
- impact: MEDIUM
4
- impactDescription: prevents schema conflicts, reduces storage size
5
- tags: client, localStorage, storage, versioning, data-minimization
6
- ---
7
-
8
- ## Version and Minimize localStorage Data
9
-
10
- Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.
11
-
12
- **Incorrect:**
13
-
14
- ```typescript
15
- // No version, stores everything, no error handling
16
- localStorage.setItem("userConfig", JSON.stringify(fullUserObject));
17
- const data = localStorage.getItem("userConfig");
18
- ```
19
-
20
- **Correct:**
21
-
22
- ```typescript
23
- const VERSION = "v2";
24
-
25
- function saveConfig(config: { theme: string; language: string }) {
26
- try {
27
- localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config));
28
- } catch {
29
- // Throws in incognito/private browsing, quota exceeded, or disabled
30
- }
31
- }
32
-
33
- function loadConfig() {
34
- try {
35
- const data = localStorage.getItem(`userConfig:${VERSION}`);
36
- return data ? JSON.parse(data) : null;
37
- } catch {
38
- return null;
39
- }
40
- }
41
-
42
- // Migration from v1 to v2
43
- function migrate() {
44
- try {
45
- const v1 = localStorage.getItem("userConfig:v1");
46
- if (v1) {
47
- const old = JSON.parse(v1);
48
- saveConfig({ theme: old.darkMode ? "dark" : "light", language: old.lang });
49
- localStorage.removeItem("userConfig:v1");
50
- }
51
- } catch {}
52
- }
53
- ```
54
-
55
- **Store minimal fields from server responses:**
56
-
57
- ```typescript
58
- // User object has 20+ fields, only store what UI needs
59
- function cachePrefs(user: FullUser) {
60
- try {
61
- localStorage.setItem(
62
- "prefs:v1",
63
- JSON.stringify({
64
- theme: user.preferences.theme,
65
- notifications: user.preferences.notifications,
66
- }),
67
- );
68
- } catch {}
69
- }
70
- ```
71
-
72
- **Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.
73
-
74
- **Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md DELETED
@@ -1,48 +0,0 @@
1
- ---
2
- title: Use Passive Event Listeners for Scrolling Performance
3
- impact: MEDIUM
4
- impactDescription: eliminates scroll delay caused by event listeners
5
- tags: client, event-listeners, scrolling, performance, touch, wheel
6
- ---
7
-
8
- ## Use Passive Event Listeners for Scrolling Performance
9
-
10
- Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.
11
-
12
- **Incorrect:**
13
-
14
- ```typescript
15
- useEffect(() => {
16
- const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
17
- const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
18
-
19
- document.addEventListener("touchstart", handleTouch);
20
- document.addEventListener("wheel", handleWheel);
21
-
22
- return () => {
23
- document.removeEventListener("touchstart", handleTouch);
24
- document.removeEventListener("wheel", handleWheel);
25
- };
26
- }, []);
27
- ```
28
-
29
- **Correct:**
30
-
31
- ```typescript
32
- useEffect(() => {
33
- const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX);
34
- const handleWheel = (e: WheelEvent) => console.log(e.deltaY);
35
-
36
- document.addEventListener("touchstart", handleTouch, { passive: true });
37
- document.addEventListener("wheel", handleWheel, { passive: true });
38
-
39
- return () => {
40
- document.removeEventListener("touchstart", handleTouch);
41
- document.removeEventListener("wheel", handleWheel);
42
- };
43
- }, []);
44
- ```
45
-
46
- **Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.
47
-
48
- **Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md DELETED
@@ -1,56 +0,0 @@
1
- ---
2
- title: Use SWR for Automatic Deduplication
3
- impact: MEDIUM-HIGH
4
- impactDescription: automatic deduplication
5
- tags: client, swr, deduplication, data-fetching
6
- ---
7
-
8
- ## Use SWR for Automatic Deduplication
9
-
10
- SWR enables request deduplication, caching, and revalidation across component instances.
11
-
12
- **Incorrect (no deduplication, each instance fetches):**
13
-
14
- ```tsx
15
- function UserList() {
16
- const [users, setUsers] = useState([]);
17
- useEffect(() => {
18
- fetch("/api/users")
19
- .then((r) => r.json())
20
- .then(setUsers);
21
- }, []);
22
- }
23
- ```
24
-
25
- **Correct (multiple instances share one request):**
26
-
27
- ```tsx
28
- import useSWR from "swr";
29
-
30
- function UserList() {
31
- const { data: users } = useSWR("/api/users", fetcher);
32
- }
33
- ```
34
-
35
- **For immutable data:**
36
-
37
- ```tsx
38
- import { useImmutableSWR } from "@/lib/swr";
39
-
40
- function StaticContent() {
41
- const { data } = useImmutableSWR("/api/config", fetcher);
42
- }
43
- ```
44
-
45
- **For mutations:**
46
-
47
- ```tsx
48
- import { useSWRMutation } from "swr/mutation";
49
-
50
- function UpdateButton() {
51
- const { trigger } = useSWRMutation("/api/user", updateUser);
52
- return <button onClick={() => trigger()}>Update</button>;
53
- }
54
- ```
55
-
56
- Reference: [https://swr.vercel.app](https://swr.vercel.app)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md DELETED
@@ -1,110 +0,0 @@
1
- ---
2
- title: Avoid Layout Thrashing
3
- impact: MEDIUM
4
- impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks
5
- tags: javascript, dom, css, performance, reflow, layout-thrashing
6
- ---
7
-
8
- ## Avoid Layout Thrashing
9
-
10
- Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
11
-
12
- **This is OK (browser batches style changes):**
13
-
14
- ```typescript
15
- function updateElementStyles(element: HTMLElement) {
16
- // Each line invalidates style, but browser batches the recalculation
17
- element.style.width = "100px";
18
- element.style.height = "200px";
19
- element.style.backgroundColor = "blue";
20
- element.style.border = "1px solid black";
21
- }
22
- ```
23
-
24
- **Incorrect (interleaved reads and writes force reflows):**
25
-
26
- ```typescript
27
- function layoutThrashing(element: HTMLElement) {
28
- element.style.width = "100px";
29
- const width = element.offsetWidth; // Forces reflow
30
- element.style.height = "200px";
31
- const height = element.offsetHeight; // Forces another reflow
32
- }
33
- ```
34
-
35
- **Correct (batch writes, then read once):**
36
-
37
- ```typescript
38
- function updateElementStyles(element: HTMLElement) {
39
- // Batch all writes together
40
- element.style.width = "100px";
41
- element.style.height = "200px";
42
- element.style.backgroundColor = "blue";
43
- element.style.border = "1px solid black";
44
-
45
- // Read after all writes are done (single reflow)
46
- const { width, height } = element.getBoundingClientRect();
47
- }
48
- ```
49
-
50
- **Correct (batch reads, then writes):**
51
-
52
- ```typescript
53
- function avoidThrashing(element: HTMLElement) {
54
- // Read phase - all layout queries first
55
- const rect1 = element.getBoundingClientRect();
56
- const offsetWidth = element.offsetWidth;
57
- const offsetHeight = element.offsetHeight;
58
-
59
- // Write phase - all style changes after
60
- element.style.width = "100px";
61
- element.style.height = "200px";
62
- }
63
- ```
64
-
65
- **Better: use CSS classes**
66
-
67
- ```css
68
- .highlighted-box {
69
- width: 100px;
70
- height: 200px;
71
- background-color: blue;
72
- border: 1px solid black;
73
- }
74
- ```
75
-
76
- ```typescript
77
- function updateElementStyles(element: HTMLElement) {
78
- element.classList.add("highlighted-box");
79
-
80
- const { width, height } = element.getBoundingClientRect();
81
- }
82
- ```
83
-
84
- **React example:**
85
-
86
- ```tsx
87
- // Incorrect: interleaving style changes with layout queries
88
- function Box({ isHighlighted }: { isHighlighted: boolean }) {
89
- const ref = useRef<HTMLDivElement>(null);
90
-
91
- useEffect(() => {
92
- if (ref.current && isHighlighted) {
93
- ref.current.style.width = "100px";
94
- const width = ref.current.offsetWidth; // Forces layout
95
- ref.current.style.height = "200px";
96
- }
97
- }, [isHighlighted]);
98
-
99
- return <div ref={ref}>Content</div>;
100
- }
101
-
102
- // Correct: toggle class
103
- function Box({ isHighlighted }: { isHighlighted: boolean }) {
104
- return <div className={isHighlighted ? "highlighted-box" : ""}>Content</div>;
105
- }
106
- ```
107
-
108
- Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
109
-
110
- See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md DELETED
@@ -1,80 +0,0 @@
1
- ---
2
- title: Cache Repeated Function Calls
3
- impact: MEDIUM
4
- impactDescription: avoid redundant computation
5
- tags: javascript, cache, memoization, performance
6
- ---
7
-
8
- ## Cache Repeated Function Calls
9
-
10
- Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.
11
-
12
- **Incorrect (redundant computation):**
13
-
14
- ```typescript
15
- function ProjectList({ projects }: { projects: Project[] }) {
16
- return (
17
- <div>
18
- {projects.map(project => {
19
- // slugify() called 100+ times for same project names
20
- const slug = slugify(project.name)
21
-
22
- return <ProjectCard key={project.id} slug={slug} />
23
- })}
24
- </div>
25
- )
26
- }
27
- ```
28
-
29
- **Correct (cached results):**
30
-
31
- ```typescript
32
- // Module-level cache
33
- const slugifyCache = new Map<string, string>()
34
-
35
- function cachedSlugify(text: string): string {
36
- if (slugifyCache.has(text)) {
37
- return slugifyCache.get(text)!
38
- }
39
- const result = slugify(text)
40
- slugifyCache.set(text, result)
41
- return result
42
- }
43
-
44
- function ProjectList({ projects }: { projects: Project[] }) {
45
- return (
46
- <div>
47
- {projects.map(project => {
48
- // Computed only once per unique project name
49
- const slug = cachedSlugify(project.name)
50
-
51
- return <ProjectCard key={project.id} slug={slug} />
52
- })}
53
- </div>
54
- )
55
- }
56
- ```
57
-
58
- **Simpler pattern for single-value functions:**
59
-
60
- ```typescript
61
- let isLoggedInCache: boolean | null = null;
62
-
63
- function isLoggedIn(): boolean {
64
- if (isLoggedInCache !== null) {
65
- return isLoggedInCache;
66
- }
67
-
68
- isLoggedInCache = document.cookie.includes("auth=");
69
- return isLoggedInCache;
70
- }
71
-
72
- // Clear cache when auth changes
73
- function onAuthChange() {
74
- isLoggedInCache = null;
75
- }
76
- ```
77
-
78
- Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
79
-
80
- Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md DELETED
@@ -1,28 +0,0 @@
1
- ---
2
- title: Cache Property Access in Loops
3
- impact: LOW-MEDIUM
4
- impactDescription: reduces lookups
5
- tags: javascript, loops, optimization, caching
6
- ---
7
-
8
- ## Cache Property Access in Loops
9
-
10
- Cache object property lookups in hot paths.
11
-
12
- **Incorrect (3 lookups × N iterations):**
13
-
14
- ```typescript
15
- for (let i = 0; i < arr.length; i++) {
16
- process(obj.config.settings.value);
17
- }
18
- ```
19
-
20
- **Correct (1 lookup total):**
21
-
22
- ```typescript
23
- const value = obj.config.settings.value;
24
- const len = arr.length;
25
- for (let i = 0; i < len; i++) {
26
- process(value);
27
- }
28
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md DELETED
@@ -1,68 +0,0 @@
1
- ---
2
- title: Cache Storage API Calls
3
- impact: LOW-MEDIUM
4
- impactDescription: reduces expensive I/O
5
- tags: javascript, localStorage, storage, caching, performance
6
- ---
7
-
8
- ## Cache Storage API Calls
9
-
10
- `localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.
11
-
12
- **Incorrect (reads storage on every call):**
13
-
14
- ```typescript
15
- function getTheme() {
16
- return localStorage.getItem("theme") ?? "light";
17
- }
18
- // Called 10 times = 10 storage reads
19
- ```
20
-
21
- **Correct (Map cache):**
22
-
23
- ```typescript
24
- const storageCache = new Map<string, string | null>();
25
-
26
- function getLocalStorage(key: string) {
27
- if (!storageCache.has(key)) {
28
- storageCache.set(key, localStorage.getItem(key));
29
- }
30
- return storageCache.get(key);
31
- }
32
-
33
- function setLocalStorage(key: string, value: string) {
34
- localStorage.setItem(key, value);
35
- storageCache.set(key, value); // keep cache in sync
36
- }
37
- ```
38
-
39
- Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.
40
-
41
- **Cookie caching:**
42
-
43
- ```typescript
44
- let cookieCache: Record<string, string> | null = null;
45
-
46
- function getCookie(name: string) {
47
- if (!cookieCache) {
48
- cookieCache = Object.fromEntries(document.cookie.split("; ").map((c) => c.split("=")));
49
- }
50
- return cookieCache[name];
51
- }
52
- ```
53
-
54
- **Important (invalidate on external changes):**
55
-
56
- If storage can change externally (another tab, server-set cookies), invalidate cache:
57
-
58
- ```typescript
59
- window.addEventListener("storage", (e) => {
60
- if (e.key) storageCache.delete(e.key);
61
- });
62
-
63
- document.addEventListener("visibilitychange", () => {
64
- if (document.visibilityState === "visible") {
65
- storageCache.clear();
66
- }
67
- });
68
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md DELETED
@@ -1,32 +0,0 @@
1
- ---
2
- title: Combine Multiple Array Iterations
3
- impact: LOW-MEDIUM
4
- impactDescription: reduces iterations
5
- tags: javascript, arrays, loops, performance
6
- ---
7
-
8
- ## Combine Multiple Array Iterations
9
-
10
- Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.
11
-
12
- **Incorrect (3 iterations):**
13
-
14
- ```typescript
15
- const admins = users.filter((u) => u.isAdmin);
16
- const testers = users.filter((u) => u.isTester);
17
- const inactive = users.filter((u) => !u.isActive);
18
- ```
19
-
20
- **Correct (1 iteration):**
21
-
22
- ```typescript
23
- const admins: User[] = [];
24
- const testers: User[] = [];
25
- const inactive: User[] = [];
26
-
27
- for (const user of users) {
28
- if (user.isAdmin) admins.push(user);
29
- if (user.isTester) testers.push(user);
30
- if (!user.isActive) inactive.push(user);
31
- }
32
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-early-exit.md DELETED
@@ -1,50 +0,0 @@
1
- ---
2
- title: Early Return from Functions
3
- impact: LOW-MEDIUM
4
- impactDescription: avoids unnecessary computation
5
- tags: javascript, functions, optimization, early-return
6
- ---
7
-
8
- ## Early Return from Functions
9
-
10
- Return early when result is determined to skip unnecessary processing.
11
-
12
- **Incorrect (processes all items even after finding answer):**
13
-
14
- ```typescript
15
- function validateUsers(users: User[]) {
16
- let hasError = false;
17
- let errorMessage = "";
18
-
19
- for (const user of users) {
20
- if (!user.email) {
21
- hasError = true;
22
- errorMessage = "Email required";
23
- }
24
- if (!user.name) {
25
- hasError = true;
26
- errorMessage = "Name required";
27
- }
28
- // Continues checking all users even after error found
29
- }
30
-
31
- return hasError ? { valid: false, error: errorMessage } : { valid: true };
32
- }
33
- ```
34
-
35
- **Correct (returns immediately on first error):**
36
-
37
- ```typescript
38
- function validateUsers(users: User[]) {
39
- for (const user of users) {
40
- if (!user.email) {
41
- return { valid: false, error: "Email required" };
42
- }
43
- if (!user.name) {
44
- return { valid: false, error: "Name required" };
45
- }
46
- }
47
-
48
- return { valid: true };
49
- }
50
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md DELETED
@@ -1,51 +0,0 @@
1
- ---
2
- title: Use flatMap to Map and Filter in One Pass
3
- impact: LOW-MEDIUM
4
- impactDescription: eliminates intermediate array
5
- tags: javascript, arrays, flatMap, filter, performance
6
- ---
7
-
8
- ## Use flatMap to Map and Filter in One Pass
9
-
10
- **Impact: LOW-MEDIUM (eliminates intermediate array)**
11
-
12
- Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.
13
-
14
- **Incorrect (2 iterations, intermediate array):**
15
-
16
- ```typescript
17
- const userNames = users.map((user) => (user.isActive ? user.name : null)).filter(Boolean);
18
- ```
19
-
20
- **Correct (1 iteration, no intermediate array):**
21
-
22
- ```typescript
23
- const userNames = users.flatMap((user) => (user.isActive ? [user.name] : []));
24
- ```
25
-
26
- **More examples:**
27
-
28
- ```typescript
29
- // Extract valid emails from responses
30
- // Before
31
- const emails = responses.map((r) => (r.success ? r.data.email : null)).filter(Boolean);
32
-
33
- // After
34
- const emails = responses.flatMap((r) => (r.success ? [r.data.email] : []));
35
-
36
- // Parse and filter valid numbers
37
- // Before
38
- const numbers = strings.map((s) => parseInt(s, 10)).filter((n) => !isNaN(n));
39
-
40
- // After
41
- const numbers = strings.flatMap((s) => {
42
- const n = parseInt(s, 10);
43
- return isNaN(n) ? [] : [n];
44
- });
45
- ```
46
-
47
- **When to use:**
48
-
49
- - Transforming items while filtering some out
50
- - Conditional mapping where some inputs produce no output
51
- - Parsing/validating where invalid inputs should be skipped
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md DELETED
@@ -1,45 +0,0 @@
1
- ---
2
- title: Hoist RegExp Creation
3
- impact: LOW-MEDIUM
4
- impactDescription: avoids recreation
5
- tags: javascript, regexp, optimization, memoization
6
- ---
7
-
8
- ## Hoist RegExp Creation
9
-
10
- Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.
11
-
12
- **Incorrect (new RegExp every render):**
13
-
14
- ```tsx
15
- function Highlighter({ text, query }: Props) {
16
- const regex = new RegExp(`(${query})`, 'gi')
17
- const parts = text.split(regex)
18
- return <>{parts.map((part, i) => ...)}</>
19
- }
20
- ```
21
-
22
- **Correct (memoize or hoist):**
23
-
24
- ```tsx
25
- const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
26
-
27
- function Highlighter({ text, query }: Props) {
28
- const regex = useMemo(
29
- () => new RegExp(`(${escapeRegex(query)})`, 'gi'),
30
- [query]
31
- )
32
- const parts = text.split(regex)
33
- return <>{parts.map((part, i) => ...)}</>
34
- }
35
- ```
36
-
37
- **Warning (global regex has mutable state):**
38
-
39
- Global regex (`/g`) has mutable `lastIndex` state:
40
-
41
- ```typescript
42
- const regex = /foo/g;
43
- regex.test("foo"); // true, lastIndex = 3
44
- regex.test("foo"); // false, lastIndex = 0
45
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-index-maps.md DELETED
@@ -1,37 +0,0 @@
1
- ---
2
- title: Build Index Maps for Repeated Lookups
3
- impact: LOW-MEDIUM
4
- impactDescription: 1M ops to 2K ops
5
- tags: javascript, map, indexing, optimization, performance
6
- ---
7
-
8
- ## Build Index Maps for Repeated Lookups
9
-
10
- Multiple `.find()` calls by the same key should use a Map.
11
-
12
- **Incorrect (O(n) per lookup):**
13
-
14
- ```typescript
15
- function processOrders(orders: Order[], users: User[]) {
16
- return orders.map((order) => ({
17
- ...order,
18
- user: users.find((u) => u.id === order.userId),
19
- }));
20
- }
21
- ```
22
-
23
- **Correct (O(1) per lookup):**
24
-
25
- ```typescript
26
- function processOrders(orders: Order[], users: User[]) {
27
- const userById = new Map(users.map((u) => [u.id, u]));
28
-
29
- return orders.map((order) => ({
30
- ...order,
31
- user: userById.get(order.userId),
32
- }));
33
- }
34
- ```
35
-
36
- Build map once (O(n)), then all lookups are O(1).
37
- For 1000 orders × 1000 users: 1M ops → 2K ops.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md DELETED
@@ -1,50 +0,0 @@
1
- ---
2
- title: Early Length Check for Array Comparisons
3
- impact: MEDIUM-HIGH
4
- impactDescription: avoids expensive operations when lengths differ
5
- tags: javascript, arrays, performance, optimization, comparison
6
- ---
7
-
8
- ## Early Length Check for Array Comparisons
9
-
10
- When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
11
-
12
- In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
13
-
14
- **Incorrect (always runs expensive comparison):**
15
-
16
- ```typescript
17
- function hasChanges(current: string[], original: string[]) {
18
- // Always sorts and joins, even when lengths differ
19
- return current.sort().join() !== original.sort().join();
20
- }
21
- ```
22
-
23
- Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
24
-
25
- **Correct (O(1) length check first):**
26
-
27
- ```typescript
28
- function hasChanges(current: string[], original: string[]) {
29
- // Early return if lengths differ
30
- if (current.length !== original.length) {
31
- return true;
32
- }
33
- // Only sort when lengths match
34
- const currentSorted = current.toSorted();
35
- const originalSorted = original.toSorted();
36
- for (let i = 0; i < currentSorted.length; i++) {
37
- if (currentSorted[i] !== originalSorted[i]) {
38
- return true;
39
- }
40
- }
41
- return false;
42
- }
43
- ```
44
-
45
- This new approach is more efficient because:
46
-
47
- - It avoids the overhead of sorting and joining the arrays when lengths differ
48
- - It avoids consuming memory for the joined strings (especially important for large arrays)
49
- - It avoids mutating the original arrays
50
- - It returns early when a difference is found
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md DELETED
@@ -1,82 +0,0 @@
1
- ---
2
- title: Use Loop for Min/Max Instead of Sort
3
- impact: LOW
4
- impactDescription: O(n) instead of O(n log n)
5
- tags: javascript, arrays, performance, sorting, algorithms
6
- ---
7
-
8
- ## Use Loop for Min/Max Instead of Sort
9
-
10
- Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.
11
-
12
- **Incorrect (O(n log n) - sort to find latest):**
13
-
14
- ```typescript
15
- interface Project {
16
- id: string;
17
- name: string;
18
- updatedAt: number;
19
- }
20
-
21
- function getLatestProject(projects: Project[]) {
22
- const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt);
23
- return sorted[0];
24
- }
25
- ```
26
-
27
- Sorts the entire array just to find the maximum value.
28
-
29
- **Incorrect (O(n log n) - sort for oldest and newest):**
30
-
31
- ```typescript
32
- function getOldestAndNewest(projects: Project[]) {
33
- const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt);
34
- return { oldest: sorted[0], newest: sorted[sorted.length - 1] };
35
- }
36
- ```
37
-
38
- Still sorts unnecessarily when only min/max are needed.
39
-
40
- **Correct (O(n) - single loop):**
41
-
42
- ```typescript
43
- function getLatestProject(projects: Project[]) {
44
- if (projects.length === 0) return null;
45
-
46
- let latest = projects[0];
47
-
48
- for (let i = 1; i < projects.length; i++) {
49
- if (projects[i].updatedAt > latest.updatedAt) {
50
- latest = projects[i];
51
- }
52
- }
53
-
54
- return latest;
55
- }
56
-
57
- function getOldestAndNewest(projects: Project[]) {
58
- if (projects.length === 0) return { oldest: null, newest: null };
59
-
60
- let oldest = projects[0];
61
- let newest = projects[0];
62
-
63
- for (let i = 1; i < projects.length; i++) {
64
- if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i];
65
- if (projects[i].updatedAt > newest.updatedAt) newest = projects[i];
66
- }
67
-
68
- return { oldest, newest };
69
- }
70
- ```
71
-
72
- Single pass through the array, no copying, no sorting.
73
-
74
- **Alternative (Math.min/Math.max for small arrays):**
75
-
76
- ```typescript
77
- const numbers = [5, 2, 8, 1, 9];
78
- const min = Math.min(...numbers);
79
- const max = Math.max(...numbers);
80
- ```
81
-
82
- This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md DELETED
@@ -1,104 +0,0 @@
1
- ---
2
- title: Defer Non-Critical Work with requestIdleCallback
3
- impact: MEDIUM
4
- impactDescription: keeps UI responsive during background tasks
5
- tags: javascript, performance, idle, scheduling, analytics
6
- ---
7
-
8
- ## Defer Non-Critical Work with requestIdleCallback
9
-
10
- **Impact: MEDIUM (keeps UI responsive during background tasks)**
11
-
12
- Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
13
-
14
- **Incorrect (blocks main thread during user interaction):**
15
-
16
- ```typescript
17
- function handleSearch(query: string) {
18
- const results = searchItems(query);
19
- setResults(results);
20
-
21
- // These block the main thread immediately
22
- analytics.track("search", { query });
23
- saveToRecentSearches(query);
24
- prefetchTopResults(results.slice(0, 3));
25
- }
26
- ```
27
-
28
- **Correct (defers non-critical work to idle time):**
29
-
30
- ```typescript
31
- function handleSearch(query: string) {
32
- const results = searchItems(query);
33
- setResults(results);
34
-
35
- // Defer non-critical work to idle periods
36
- requestIdleCallback(() => {
37
- analytics.track("search", { query });
38
- });
39
-
40
- requestIdleCallback(() => {
41
- saveToRecentSearches(query);
42
- });
43
-
44
- requestIdleCallback(() => {
45
- prefetchTopResults(results.slice(0, 3));
46
- });
47
- }
48
- ```
49
-
50
- **With timeout for required work:**
51
-
52
- ```typescript
53
- // Ensure analytics fires within 2 seconds even if browser stays busy
54
- requestIdleCallback(() => analytics.track("page_view", { path: location.pathname }), {
55
- timeout: 2000,
56
- });
57
- ```
58
-
59
- **Chunking large tasks:**
60
-
61
- ```typescript
62
- function processLargeDataset(items: Item[]) {
63
- let index = 0;
64
-
65
- function processChunk(deadline: IdleDeadline) {
66
- // Process items while we have idle time (aim for <50ms chunks)
67
- while (index < items.length && deadline.timeRemaining() > 0) {
68
- processItem(items[index]);
69
- index++;
70
- }
71
-
72
- // Schedule next chunk if more items remain
73
- if (index < items.length) {
74
- requestIdleCallback(processChunk);
75
- }
76
- }
77
-
78
- requestIdleCallback(processChunk);
79
- }
80
- ```
81
-
82
- **With fallback for unsupported browsers:**
83
-
84
- ```typescript
85
- const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1));
86
-
87
- scheduleIdleWork(() => {
88
- // Non-critical work
89
- });
90
- ```
91
-
92
- **When to use:**
93
-
94
- - Analytics and telemetry
95
- - Saving state to localStorage/IndexedDB
96
- - Prefetching resources for likely next actions
97
- - Processing non-urgent data transformations
98
- - Lazy initialization of non-critical features
99
-
100
- **When NOT to use:**
101
-
102
- - User-initiated actions that need immediate feedback
103
- - Rendering updates the user is waiting for
104
- - Time-sensitive operations
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md DELETED
@@ -1,24 +0,0 @@
1
- ---
2
- title: Use Set/Map for O(1) Lookups
3
- impact: LOW-MEDIUM
4
- impactDescription: O(n) to O(1)
5
- tags: javascript, set, map, data-structures, performance
6
- ---
7
-
8
- ## Use Set/Map for O(1) Lookups
9
-
10
- Convert arrays to Set/Map for repeated membership checks.
11
-
12
- **Incorrect (O(n) per check):**
13
-
14
- ```typescript
15
- const allowedIds = ['a', 'b', 'c', ...]
16
- items.filter(item => allowedIds.includes(item.id))
17
- ```
18
-
19
- **Correct (O(1) per check):**
20
-
21
- ```typescript
22
- const allowedIds = new Set(['a', 'b', 'c', ...])
23
- items.filter(item => allowedIds.has(item.id))
24
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md DELETED
@@ -1,57 +0,0 @@
1
- ---
2
- title: Use toSorted() Instead of sort() for Immutability
3
- impact: MEDIUM-HIGH
4
- impactDescription: prevents mutation bugs in React state
5
- tags: javascript, arrays, immutability, react, state, mutation
6
- ---
7
-
8
- ## Use toSorted() Instead of sort() for Immutability
9
-
10
- `.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
11
-
12
- **Incorrect (mutates original array):**
13
-
14
- ```typescript
15
- function UserList({ users }: { users: User[] }) {
16
- // Mutates the users prop array!
17
- const sorted = useMemo(
18
- () => users.sort((a, b) => a.name.localeCompare(b.name)),
19
- [users]
20
- )
21
- return <div>{sorted.map(renderUser)}</div>
22
- }
23
- ```
24
-
25
- **Correct (creates new array):**
26
-
27
- ```typescript
28
- function UserList({ users }: { users: User[] }) {
29
- // Creates new sorted array, original unchanged
30
- const sorted = useMemo(
31
- () => users.toSorted((a, b) => a.name.localeCompare(b.name)),
32
- [users]
33
- )
34
- return <div>{sorted.map(renderUser)}</div>
35
- }
36
- ```
37
-
38
- **Why this matters in React:**
39
-
40
- 1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
41
- 2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
42
-
43
- **Browser support (fallback for older browsers):**
44
-
45
- `.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
46
-
47
- ```typescript
48
- // Fallback for older browsers
49
- const sorted = [...items].sort((a, b) => a.value - b.value);
50
- ```
51
-
52
- **Other immutable array methods:**
53
-
54
- - `.toSorted()` - immutable sort
55
- - `.toReversed()` - immutable reverse
56
- - `.toSpliced()` - immutable splice
57
- - `.with()` - immutable element replacement
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-activity.md DELETED
@@ -1,26 +0,0 @@
1
- ---
2
- title: Use Activity Component for Show/Hide
3
- impact: MEDIUM
4
- impactDescription: preserves state/DOM
5
- tags: rendering, activity, visibility, state-preservation
6
- ---
7
-
8
- ## Use Activity Component for Show/Hide
9
-
10
- Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.
11
-
12
- **Usage:**
13
-
14
- ```tsx
15
- import { Activity } from "react";
16
-
17
- function Dropdown({ isOpen }: Props) {
18
- return (
19
- <Activity mode={isOpen ? "visible" : "hidden"}>
20
- <ExpensiveMenu />
21
- </Activity>
22
- );
23
- }
24
- ```
25
-
26
- Avoids expensive re-renders and state loss.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md DELETED
@@ -1,38 +0,0 @@
1
- ---
2
- title: Animate SVG Wrapper Instead of SVG Element
3
- impact: LOW
4
- impactDescription: enables hardware acceleration
5
- tags: rendering, svg, css, animation, performance
6
- ---
7
-
8
- ## Animate SVG Wrapper Instead of SVG Element
9
-
10
- Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.
11
-
12
- **Incorrect (animating SVG directly - no hardware acceleration):**
13
-
14
- ```tsx
15
- function LoadingSpinner() {
16
- return (
17
- <svg className="animate-spin" width="24" height="24" viewBox="0 0 24 24">
18
- <circle cx="12" cy="12" r="10" stroke="currentColor" />
19
- </svg>
20
- );
21
- }
22
- ```
23
-
24
- **Correct (animating wrapper div - hardware accelerated):**
25
-
26
- ```tsx
27
- function LoadingSpinner() {
28
- return (
29
- <div className="animate-spin">
30
- <svg width="24" height="24" viewBox="0 0 24 24">
31
- <circle cx="12" cy="12" r="10" stroke="currentColor" />
32
- </svg>
33
- </div>
34
- );
35
- }
36
- ```
37
-
38
- This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md DELETED
@@ -1,32 +0,0 @@
1
- ---
2
- title: Use Explicit Conditional Rendering
3
- impact: LOW
4
- impactDescription: prevents rendering 0 or NaN
5
- tags: rendering, conditional, jsx, falsy-values
6
- ---
7
-
8
- ## Use Explicit Conditional Rendering
9
-
10
- Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
11
-
12
- **Incorrect (renders "0" when count is 0):**
13
-
14
- ```tsx
15
- function Badge({ count }: { count: number }) {
16
- return <div>{count && <span className="badge">{count}</span>}</div>;
17
- }
18
-
19
- // When count = 0, renders: <div>0</div>
20
- // When count = 5, renders: <div><span class="badge">5</span></div>
21
- ```
22
-
23
- **Correct (renders nothing when count is 0):**
24
-
25
- ```tsx
26
- function Badge({ count }: { count: number }) {
27
- return <div>{count > 0 ? <span className="badge">{count}</span> : null}</div>;
28
- }
29
-
30
- // When count = 0, renders: <div></div>
31
- // When count = 5, renders: <div><span class="badge">5</span></div>
32
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md DELETED
@@ -1,38 +0,0 @@
1
- ---
2
- title: CSS content-visibility for Long Lists
3
- impact: HIGH
4
- impactDescription: faster initial render
5
- tags: rendering, css, content-visibility, long-lists
6
- ---
7
-
8
- ## CSS content-visibility for Long Lists
9
-
10
- Apply `content-visibility: auto` to defer off-screen rendering.
11
-
12
- **CSS:**
13
-
14
- ```css
15
- .message-item {
16
- content-visibility: auto;
17
- contain-intrinsic-size: 0 80px;
18
- }
19
- ```
20
-
21
- **Example:**
22
-
23
- ```tsx
24
- function MessageList({ messages }: { messages: Message[] }) {
25
- return (
26
- <div className="overflow-y-auto h-screen">
27
- {messages.map((msg) => (
28
- <div key={msg.id} className="message-item">
29
- <Avatar user={msg.author} />
30
- <div>{msg.content}</div>
31
- </div>
32
- ))}
33
- </div>
34
- );
35
- }
36
- ```
37
-
38
- For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md DELETED
@@ -1,36 +0,0 @@
1
- ---
2
- title: Hoist Static JSX Elements
3
- impact: LOW
4
- impactDescription: avoids re-creation
5
- tags: rendering, jsx, static, optimization
6
- ---
7
-
8
- ## Hoist Static JSX Elements
9
-
10
- Extract static JSX outside components to avoid re-creation.
11
-
12
- **Incorrect (recreates element every render):**
13
-
14
- ```tsx
15
- function LoadingSkeleton() {
16
- return <div className="animate-pulse h-20 bg-gray-200" />;
17
- }
18
-
19
- function Container() {
20
- return <div>{loading && <LoadingSkeleton />}</div>;
21
- }
22
- ```
23
-
24
- **Correct (reuses same element):**
25
-
26
- ```tsx
27
- const loadingSkeleton = <div className="animate-pulse h-20 bg-gray-200" />;
28
-
29
- function Container() {
30
- return <div>{loading && loadingSkeleton}</div>;
31
- }
32
- ```
33
-
34
- This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
35
-
36
- **Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md DELETED
@@ -1,72 +0,0 @@
1
- ---
2
- title: Prevent Hydration Mismatch Without Flickering
3
- impact: MEDIUM
4
- impactDescription: avoids visual flicker and hydration errors
5
- tags: rendering, ssr, hydration, localStorage, flicker
6
- ---
7
-
8
- ## Prevent Hydration Mismatch Without Flickering
9
-
10
- When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
11
-
12
- **Incorrect (breaks SSR):**
13
-
14
- ```tsx
15
- function ThemeWrapper({ children }: { children: ReactNode }) {
16
- // localStorage is not available on server - throws error
17
- const theme = localStorage.getItem("theme") || "light";
18
-
19
- return <div className={theme}>{children}</div>;
20
- }
21
- ```
22
-
23
- Server-side rendering will fail because `localStorage` is undefined.
24
-
25
- **Incorrect (visual flickering):**
26
-
27
- ```tsx
28
- function ThemeWrapper({ children }: { children: ReactNode }) {
29
- const [theme, setTheme] = useState("light");
30
-
31
- useEffect(() => {
32
- // Runs after hydration - causes visible flash
33
- const stored = localStorage.getItem("theme");
34
- if (stored) {
35
- setTheme(stored);
36
- }
37
- }, []);
38
-
39
- return <div className={theme}>{children}</div>;
40
- }
41
- ```
42
-
43
- Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
44
-
45
- **Correct (no flicker, no hydration mismatch):**
46
-
47
- ```tsx
48
- function ThemeWrapper({ children }: { children: ReactNode }) {
49
- return (
50
- <>
51
- <div id="theme-wrapper">{children}</div>
52
- <script
53
- dangerouslySetInnerHTML={{
54
- __html: `
55
- (function() {
56
- try {
57
- var theme = localStorage.getItem('theme') || 'light';
58
- var el = document.getElementById('theme-wrapper');
59
- if (el) el.className = theme;
60
- } catch (e) {}
61
- })();
62
- `,
63
- }}
64
- />
65
- </>
66
- );
67
- }
68
- ```
69
-
70
- The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
71
-
72
- This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md DELETED
@@ -1,26 +0,0 @@
1
- ---
2
- title: Suppress Expected Hydration Mismatches
3
- impact: LOW-MEDIUM
4
- impactDescription: avoids noisy hydration warnings for known differences
5
- tags: rendering, hydration, ssr, nextjs
6
- ---
7
-
8
- ## Suppress Expected Hydration Mismatches
9
-
10
- In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these _expected_ mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
11
-
12
- **Incorrect (known mismatch warnings):**
13
-
14
- ```tsx
15
- function Timestamp() {
16
- return <span>{new Date().toLocaleString()}</span>;
17
- }
18
- ```
19
-
20
- **Correct (suppress expected mismatch only):**
21
-
22
- ```tsx
23
- function Timestamp() {
24
- return <span suppressHydrationWarning>{new Date().toLocaleString()}</span>;
25
- }
26
- ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md DELETED
@@ -1,85 +0,0 @@
1
- ---
2
- title: Use React DOM Resource Hints
3
- impact: HIGH
4
- impactDescription: reduces load time for critical resources
5
- tags: rendering, preload, preconnect, prefetch, resource-hints
6
- ---
7
-
8
- ## Use React DOM Resource Hints
9
-
10
- **Impact: HIGH (reduces load time for critical resources)**
11
-
12
- React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
13
-
14
- - **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
15
- - **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
16
- - **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
17
- - **`preloadModule(href)`**: Fetch an ES module you'll use soon
18
- - **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
19
- - **`preinitModule(href)`**: Fetch and evaluate an ES module
20
-
21
- **Example (preconnect to third-party APIs):**
22
-
23
- ```tsx
24
- import { preconnect, prefetchDNS } from "react-dom";
25
-
26
- export default function App() {
27
- prefetchDNS("https://analytics.example.com");
28
- preconnect("https://api.example.com");
29
-
30
- return <main>{/* content */}</main>;
31
- }
32
- ```
33
-
34
- **Example (preload critical fonts and styles):**
35
-
36
- ```tsx
37
- import { preload, preinit } from "react-dom";
38
-
39
- export default function RootLayout({ children }) {
40
- // Preload font file
41
- preload("/fonts/inter.woff2", { as: "font", type: "font/woff2", crossOrigin: "anonymous" });
42
-
43
- // Fetch and apply critical stylesheet immediately
44
- preinit("/styles/critical.css", { as: "style" });
45
-
46
- return (
47
- <html>
48
- <body>{children}</body>
49
- </html>
50
- );
51
- }
52
- ```
53
-
54
- **Example (preload modules for code-split routes):**
55
-
56
- ```tsx
57
- import { preloadModule, preinitModule } from "react-dom";
58
-
59
- function Navigation() {
60
- const preloadDashboard = () => {
61
- preloadModule("/dashboard.js", { as: "script" });
62
- };
63
-
64
- return (
65
- <nav>
66
- <a href="/dashboard" onMouseEnter={preloadDashboard}>
67
- Dashboard
68
- </a>
69
- </nav>
70
- );
71
- }
72
- ```
73
-
74
- **When to use each:**
75
-
76
- | API | Use case |
77
- | --------------- | ------------------------------------------- |
78
- | `prefetchDNS` | Third-party domains you'll connect to later |
79
- | `preconnect` | APIs or CDNs you'll fetch from immediately |
80
- | `preload` | Critical resources needed for current page |
81
- | `preloadModule` | JS modules for likely next navigation |
82
- | `preinit` | Stylesheets/scripts that must execute early |
83
- | `preinitModule` | ES modules that must execute early |
84
-
85
- Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md DELETED
@@ -1,68 +0,0 @@
1
- ---
2
- title: Use defer or async on Script Tags
3
- impact: HIGH
4
- impactDescription: eliminates render-blocking
5
- tags: rendering, script, defer, async, performance
6
- ---
7
-
8
- ## Use defer or async on Script Tags
9
-
10
- **Impact: HIGH (eliminates render-blocking)**
11
-
12
- Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
13
-
14
- - **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
15
- - **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
16
-
17
- Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
18
-
19
- **Incorrect (blocks rendering):**
20
-
21
- ```tsx
22
- export default function Document() {
23
- return (
24
- <html>
25
- <head>
26
- <script src="https://example.com/analytics.js" />
27
- <script src="/scripts/utils.js" />
28
- </head>
29
- <body>{/* content */}</body>
30
- </html>
31
- );
32
- }
33
- ```
34
-
35
- **Correct (non-blocking):**
36
-
37
- ```tsx
38
- export default function Document() {
39
- return (
40
- <html>
41
- <head>
42
- {/* Independent script - use async */}
43
- <script src="https://example.com/analytics.js" async />
44
- {/* DOM-dependent script - use defer */}
45
- <script src="/scripts/utils.js" defer />
46
- </head>
47
- <body>{/* content */}</body>
48
- </html>
49
- );
50
- }
51
- ```
52
-
53
- **Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:
54
-
55
- ```tsx
56
- import Script from "next/script";
57
-
58
- export default function Page() {
59
- return (
60
- <>
61
- <Script src="https://example.com/analytics.js" strategy="afterInteractive" />
62
- <Script src="/scripts/utils.js" strategy="beforeInteractive" />
63
- </>
64
- );
65
- }
66
- ```
67
-
68
- Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md DELETED
@@ -1,28 +0,0 @@
1
- ---
2
- title: Optimize SVG Precision
3
- impact: LOW
4
- impactDescription: reduces file size
5
- tags: rendering, svg, optimization, svgo
6
- ---
7
-
8
- ## Optimize SVG Precision
9
-
10
- Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
11
-
12
- **Incorrect (excessive precision):**
13
-
14
- ```svg
15
- <path d="M 10.293847 20.847362 L 30.938472 40.192837" />
16
- ```
17
-
18
- **Correct (1 decimal place):**
19
-
20
- ```svg
21
- <path d="M 10.3 20.8 L 30.9 40.2" />
22
- ```
23
-
24
- **Automate with SVGO:**
25
-
26
- ```bash
27
- npx svgo --precision=1 --multipass icon.svg
28
- ```