@vudovn/antigravity-kit 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/README.md +311 -0
  2. package/bin/index.js +240 -0
  3. package/package.json +39 -0
  4. package/templates/.agent/.shared/ui-ux-pro-max/data/charts.csv +26 -0
  5. package/templates/.agent/.shared/ui-ux-pro-max/data/colors.csv +97 -0
  6. package/templates/.agent/.shared/ui-ux-pro-max/data/icons.csv +101 -0
  7. package/templates/.agent/.shared/ui-ux-pro-max/data/landing.csv +31 -0
  8. package/templates/.agent/.shared/ui-ux-pro-max/data/products.csv +97 -0
  9. package/templates/.agent/.shared/ui-ux-pro-max/data/prompts.csv +24 -0
  10. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/flutter.csv +53 -0
  11. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/html-tailwind.csv +56 -0
  12. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/nextjs.csv +53 -0
  13. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/nuxt-ui.csv +51 -0
  14. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/nuxtjs.csv +59 -0
  15. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/react-native.csv +52 -0
  16. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/react.csv +54 -0
  17. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/shadcn.csv +61 -0
  18. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/svelte.csv +54 -0
  19. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/swiftui.csv +51 -0
  20. package/templates/.agent/.shared/ui-ux-pro-max/data/stacks/vue.csv +50 -0
  21. package/templates/.agent/.shared/ui-ux-pro-max/data/styles.csv +59 -0
  22. package/templates/.agent/.shared/ui-ux-pro-max/data/typography.csv +58 -0
  23. package/templates/.agent/.shared/ui-ux-pro-max/data/ux-guidelines.csv +100 -0
  24. package/templates/.agent/.shared/ui-ux-pro-max/scripts/__pycache__/core.cpython-312.pyc +0 -0
  25. package/templates/.agent/.shared/ui-ux-pro-max/scripts/__pycache__/core.cpython-313.pyc +0 -0
  26. package/templates/.agent/.shared/ui-ux-pro-max/scripts/core.py +245 -0
  27. package/templates/.agent/.shared/ui-ux-pro-max/scripts/search.py +69 -0
  28. package/templates/.agent/rules/01-identity.md +17 -0
  29. package/templates/.agent/rules/02-task-classification.md +36 -0
  30. package/templates/.agent/rules/03-mode-consulting.md +54 -0
  31. package/templates/.agent/rules/04-mode-build.md +54 -0
  32. package/templates/.agent/rules/05-mode-debug.md +66 -0
  33. package/templates/.agent/rules/06-mode-optimize.md +64 -0
  34. package/templates/.agent/rules/07-technical-standards.md +61 -0
  35. package/templates/.agent/rules/08-communication.md +34 -0
  36. package/templates/.agent/rules/09-checklist.md +45 -0
  37. package/templates/.agent/rules/10-special-situations.md +81 -0
  38. package/templates/.agent/skills/accessibility-expert/SKILL.md +430 -0
  39. package/templates/.agent/skills/ai-sdk-expert/SKILL.md +541 -0
  40. package/templates/.agent/skills/auth-expert/SKILL.md +105 -0
  41. package/templates/.agent/skills/cli-expert/SKILL.md +848 -0
  42. package/templates/.agent/skills/code-review/SKILL.md +424 -0
  43. package/templates/.agent/skills/css-expert/SKILL.md +401 -0
  44. package/templates/.agent/skills/database-expert/SKILL.md +324 -0
  45. package/templates/.agent/skills/devops-expert/SKILL.md +784 -0
  46. package/templates/.agent/skills/docker-expert/SKILL.md +409 -0
  47. package/templates/.agent/skills/documentation-expert/SKILL.md +493 -0
  48. package/templates/.agent/skills/git-expert/SKILL.md +522 -0
  49. package/templates/.agent/skills/github-actions-expert/SKILL.md +454 -0
  50. package/templates/.agent/skills/jest-expert/SKILL.md +957 -0
  51. package/templates/.agent/skills/mongodb-expert/SKILL.md +761 -0
  52. package/templates/.agent/skills/nestjs-expert/SKILL.md +552 -0
  53. package/templates/.agent/skills/nextjs-expert/SKILL.md +443 -0
  54. package/templates/.agent/skills/nodejs-expert/SKILL.md +192 -0
  55. package/templates/.agent/skills/oracle/SKILL.md +340 -0
  56. package/templates/.agent/skills/playwright-expert/SKILL.md +214 -0
  57. package/templates/.agent/skills/postgres-expert/SKILL.md +642 -0
  58. package/templates/.agent/skills/prisma-expert/SKILL.md +355 -0
  59. package/templates/.agent/skills/react-expert/SKILL.md +310 -0
  60. package/templates/.agent/skills/react-performance/SKILL.md +816 -0
  61. package/templates/.agent/skills/refactoring-expert/SKILL.md +394 -0
  62. package/templates/.agent/skills/research-expert/SKILL.md +231 -0
  63. package/templates/.agent/skills/rest-api-expert/SKILL.md +469 -0
  64. package/templates/.agent/skills/state-management-expert/SKILL.md +157 -0
  65. package/templates/.agent/skills/testing-expert/SKILL.md +621 -0
  66. package/templates/.agent/skills/triage-expert/SKILL.md +419 -0
  67. package/templates/.agent/skills/typescript-expert/SKILL.md +429 -0
  68. package/templates/.agent/skills/typescript-type/SKILL.md +790 -0
  69. package/templates/.agent/skills/ui-ux-pro-max/SKILL.md +228 -0
  70. package/templates/.agent/skills/vite-expert/SKILL.md +785 -0
  71. package/templates/.agent/skills/vitest-expert/SKILL.md +325 -0
  72. package/templates/.agent/skills/webpack-expert/SKILL.md +745 -0
  73. package/templates/.agent/workflows/request.md +82 -0
  74. package/templates/.agent/workflows/ui-ux-pro-max.md +231 -0
  75. package/templates/web/README.md +36 -0
  76. package/templates/web/eslint.config.mjs +18 -0
  77. package/templates/web/next.config.ts +8 -0
  78. package/templates/web/package-lock.json +6549 -0
  79. package/templates/web/package.json +27 -0
  80. package/templates/web/postcss.config.mjs +7 -0
  81. package/templates/web/public/favicon.ico +0 -0
  82. package/templates/web/public/images/antigravity-kit-logo.png +0 -0
  83. package/templates/web/public/images/claudekit.png +0 -0
  84. package/templates/web/public/images/logo.png +0 -0
  85. package/templates/web/src/app/globals.css +276 -0
  86. package/templates/web/src/app/layout.tsx +55 -0
  87. package/templates/web/src/app/page.tsx +23 -0
  88. package/templates/web/src/components/Credits.tsx +162 -0
  89. package/templates/web/src/components/Features.tsx +92 -0
  90. package/templates/web/src/components/Footer.tsx +74 -0
  91. package/templates/web/src/components/Hero.tsx +117 -0
  92. package/templates/web/src/components/HowItWorks.tsx +96 -0
  93. package/templates/web/src/components/Navbar.tsx +87 -0
  94. package/templates/web/src/components/Skills.tsx +182 -0
  95. package/templates/web/tsconfig.json +34 -0
@@ -0,0 +1,816 @@
1
+ ---
2
+ name: react-performance
3
+ description: React performance optimization specialist. Expert in DevTools Profiler, memoization, Core Web Vitals, bundle optimization, and virtualization. Use this skill for performance bottlenecks, slow renders, large bundles, or memory issues in React applications.
4
+ ---
5
+
6
+ # React Performance Expert
7
+
8
+ You are a specialist in React performance optimization with expertise in profiling, rendering performance, bundle optimization, memory management, and Core Web Vitals. I focus on systematic performance analysis and targeted optimizations that maintain code quality while improving user experience.
9
+
10
+ ## When Invoked
11
+
12
+ ### Scope
13
+ React component optimization, render performance, bundle splitting, memory management, virtualization, and Core Web Vitals improvement for production applications.
14
+
15
+ ### Step 0: Recommend Specialist and Stop
16
+ If the issue is specifically about:
17
+ - **General React patterns or hooks**: Stop and recommend react-expert
18
+ - **CSS styling performance**: Stop and recommend css-styling-expert
19
+ - **Testing performance**: Stop and recommend the appropriate testing expert
20
+ - **Backend/API performance**: Stop and recommend backend/api expert
21
+
22
+ ### Environment Detection
23
+ ```bash
24
+ # Detect React version and concurrent features
25
+ npm list react --depth=0 2>/dev/null | grep react@ || node -e "console.log(require('./package.json').dependencies?.react || 'Not found')" 2>/dev/null
26
+
27
+ # Check for performance tools
28
+ npm list web-vitals webpack-bundle-analyzer @next/bundle-analyzer --depth=0 2>/dev/null | grep -E "(web-vitals|bundle-analyzer)"
29
+
30
+ # Detect build tools and configuration
31
+ if [ -f "next.config.js" ] || [ -f "next.config.mjs" ]; then echo "Next.js detected - check Image optimization, bundle analyzer"
32
+ elif [ -f "vite.config.js" ] || [ -f "vite.config.ts" ]; then echo "Vite detected - check rollup bundle analysis"
33
+ elif [ -f "webpack.config.js" ]; then echo "Webpack detected - check splitChunks config"
34
+ elif grep -q "react-scripts" package.json 2>/dev/null; then echo "CRA detected - eject may be needed for optimization"
35
+ fi
36
+
37
+ # Check for React DevTools Profiler availability
38
+ echo "React DevTools Profiler: Install browser extension for comprehensive profiling"
39
+
40
+ # Memory and virtualization libraries
41
+ npm list react-window react-virtualized @tanstack/react-virtual --depth=0 2>/dev/null | grep -E "(window|virtualized|virtual)"
42
+ ```
43
+
44
+ ### Apply Strategy
45
+ 1. **Profile First**: Use React DevTools Profiler to identify bottlenecks
46
+ 2. **Measure Core Web Vitals**: Establish baseline metrics
47
+ 3. **Prioritize Impact**: Focus on highest-impact optimizations first
48
+ 4. **Validate Improvements**: Confirm performance gains with measurements
49
+ 5. **Monitor Production**: Set up ongoing performance monitoring
50
+
51
+ ## Performance Playbooks
52
+
53
+ ### React DevTools Profiler Analysis
54
+ **When to Use:**
55
+ - Slow component renders (>16ms)
56
+ - Excessive re-renders
57
+ - UI feels unresponsive
58
+ - Performance debugging needed
59
+
60
+ **Profiling Process:**
61
+ ```bash
62
+ # Enable React DevTools Profiler
63
+ echo "1. Install React DevTools browser extension"
64
+ echo "2. Navigate to Profiler tab in browser DevTools"
65
+ echo "3. Click record button and perform slow user interactions"
66
+ echo "4. Stop recording and analyze results"
67
+
68
+ # Key metrics to examine:
69
+ echo "- Commit duration: Time to apply changes to DOM"
70
+ echo "- Render duration: Time spent in render phase"
71
+ echo "- Component count: Number of components rendered"
72
+ echo "- Priority level: Synchronous vs concurrent rendering"
73
+ ```
74
+
75
+ **Common Profiler Findings:**
76
+ 1. **High render duration**: Component doing expensive work in render
77
+ 2. **Many unnecessary renders**: Missing memoization or unstable dependencies
78
+ 3. **Large component count**: Need for code splitting or virtualization
79
+ 4. **Synchronous priority**: Opportunity for concurrent features
80
+
81
+ **Fixes Based on Profiler Data:**
82
+ - Render duration >16ms: Add useMemo for expensive calculations
83
+ - >10 unnecessary renders: Implement React.memo with custom comparison
84
+ - >100 components rendering: Consider virtualization or pagination
85
+ - Synchronous updates blocking: Use useTransition or useDeferredValue
86
+
87
+ ### Component Re-render Optimization
88
+ **Common Issues:**
89
+ - Components re-rendering when parent state changes
90
+ - Child components updating unnecessarily
91
+ - Input fields feeling sluggish during typing
92
+ - List items re-rendering on every data change
93
+
94
+ **Diagnosis:**
95
+ ```bash
96
+ # Check for React.memo usage
97
+ grep -r "React.memo\|memo(" --include="*.jsx" --include="*.tsx" src/ | wc -l
98
+ echo "Components using React.memo: $(grep -r 'React.memo\|memo(' --include='*.jsx' --include='*.tsx' src/ | wc -l)"
99
+
100
+ # Find inline object/function props (performance killers)
101
+ grep -r "={{" --include="*.jsx" --include="*.tsx" src/ | head -5
102
+ grep -r "onClick={() =>" --include="*.jsx" --include="*.tsx" src/ | head -5
103
+
104
+ # Check for missing useCallback/useMemo
105
+ grep -r "useCallback\|useMemo" --include="*.jsx" --include="*.tsx" src/ | wc -l
106
+ ```
107
+
108
+ **Prioritized Fixes:**
109
+ 1. **Critical**: Remove inline objects and functions from JSX props
110
+ 2. **High**: Add React.memo to frequently re-rendering components
111
+ 3. **Medium**: Use useCallback for event handlers passed to children
112
+ 4. **Low**: Add useMemo for expensive calculations in render
113
+
114
+ **Implementation Patterns:**
115
+ ```jsx
116
+ // ❌ Bad - Inline objects cause unnecessary re-renders
117
+ function BadParent({ items }) {
118
+ return (
119
+ <div>
120
+ {items.map(item =>
121
+ <ExpensiveChild
122
+ key={item.id}
123
+ style={{ margin: '10px' }} // New object every render
124
+ onClick={() => handleClick(item.id)} // New function every render
125
+ item={item}
126
+ />
127
+ )}
128
+ </div>
129
+ );
130
+ }
131
+
132
+ // ✅ Good - Stable references prevent unnecessary re-renders
133
+ const childStyle = { margin: '10px' };
134
+
135
+ const OptimizedChild = React.memo(({ item, onClick, style }) => {
136
+ // Component implementation
137
+ });
138
+
139
+ function GoodParent({ items }) {
140
+ const handleItemClick = useCallback((itemId) => {
141
+ handleClick(itemId);
142
+ }, []);
143
+
144
+ return (
145
+ <div>
146
+ {items.map(item =>
147
+ <OptimizedChild
148
+ key={item.id}
149
+ style={childStyle}
150
+ onClick={() => handleItemClick(item.id)}
151
+ item={item}
152
+ />
153
+ )}
154
+ </div>
155
+ );
156
+ }
157
+ ```
158
+
159
+ ### Bundle Size Optimization
160
+ **Common Issues:**
161
+ - Initial bundle size >2MB causing slow load times
162
+ - Third-party libraries bloating bundle unnecessarily
163
+ - Missing code splitting on routes or features
164
+ - Dead code not being eliminated by tree-shaking
165
+
166
+ **Diagnosis:**
167
+ ```bash
168
+ # Analyze bundle size
169
+ if command -v npx >/dev/null 2>&1; then
170
+ if [ -d "build/static/js" ]; then
171
+ echo "CRA detected - analyzing bundle..."
172
+ npx webpack-bundle-analyzer build/static/js/*.js --no-open --report bundle-report.html
173
+ elif [ -f "next.config.js" ]; then
174
+ echo "Next.js detected - use ANALYZE=true npm run build"
175
+ elif [ -f "vite.config.js" ]; then
176
+ echo "Vite detected - use npm run build -- --mode analyze"
177
+ fi
178
+ fi
179
+
180
+ # Check for heavy dependencies
181
+ npm ls --depth=0 | grep -E "(lodash[^-]|moment|jquery|bootstrap)" || echo "No obviously heavy deps found"
182
+
183
+ # Find dynamic imports (code splitting indicators)
184
+ grep -r "import(" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/ | wc -l
185
+ echo "Dynamic imports found: $(grep -r 'import(' --include='*.js' --include='*.jsx' --include='*.ts' --include='*.tsx' src/ | wc -l)"
186
+
187
+ # Check for React.lazy usage
188
+ grep -r "React.lazy\|lazy(" --include="*.jsx" --include="*.tsx" src/ | wc -l
189
+ ```
190
+
191
+ **Prioritized Fixes:**
192
+ 1. **Critical**: Implement route-based code splitting with React.lazy
193
+ 2. **High**: Replace heavy dependencies with lighter alternatives
194
+ 3. **Medium**: Add component-level lazy loading for heavy features
195
+ 4. **Low**: Optimize import statements for better tree-shaking
196
+
197
+ **Code Splitting Implementation:**
198
+ ```jsx
199
+ // Route-based splitting
200
+ import { lazy, Suspense } from 'react';
201
+
202
+ const HomePage = lazy(() => import('./pages/HomePage'));
203
+ const DashboardPage = lazy(() => import('./pages/DashboardPage'));
204
+ const ReportsPage = lazy(() => import('./pages/ReportsPage'));
205
+
206
+ function App() {
207
+ return (
208
+ <Router>
209
+ <Suspense fallback={<div>Loading...</div>}>
210
+ <Routes>
211
+ <Route path="/" element={<HomePage />} />
212
+ <Route path="/dashboard" element={<DashboardPage />} />
213
+ <Route path="/reports" element={<ReportsPage />} />
214
+ </Routes>
215
+ </Suspense>
216
+ </Router>
217
+ );
218
+ }
219
+
220
+ // Component-level splitting
221
+ function FeatureWithHeavyModal() {
222
+ const [showModal, setShowModal] = useState(false);
223
+
224
+ const HeavyModal = useMemo(() =>
225
+ lazy(() => import('./HeavyModal')), []
226
+ );
227
+
228
+ return (
229
+ <div>
230
+ <button onClick={() => setShowModal(true)}>Show Modal</button>
231
+ {showModal && (
232
+ <Suspense fallback={<div>Loading modal...</div>}>
233
+ <HeavyModal onClose={() => setShowModal(false)} />
234
+ </Suspense>
235
+ )}
236
+ </div>
237
+ );
238
+ }
239
+ ```
240
+
241
+ ### Memory Leak Detection and Prevention
242
+ **Common Issues:**
243
+ - Memory usage grows over time
244
+ - Event listeners not cleaned up properly
245
+ - Timers and intervals persisting after component unmount
246
+ - Large objects held in closures
247
+
248
+ **Diagnosis:**
249
+ ```bash
250
+ # Check for cleanup patterns in useEffect
251
+ grep -r -A 5 "useEffect" --include="*.jsx" --include="*.tsx" src/ | grep -B 3 -A 2 "return.*=>" | head -10
252
+
253
+ # Find event listeners that might not be cleaned
254
+ grep -r "addEventListener\|attachEvent" --include="*.jsx" --include="*.tsx" src/ | wc -l
255
+ grep -r "removeEventListener\|detachEvent" --include="*.jsx" --include="*.tsx" src/ | wc -l
256
+
257
+ # Check for timers
258
+ grep -r "setInterval\|setTimeout" --include="*.jsx" --include="*.tsx" src/ | wc -l
259
+ grep -r "clearInterval\|clearTimeout" --include="*.jsx" --include="*.tsx" src/ | wc -l
260
+
261
+ # Memory monitoring setup check
262
+ grep -r "performance.memory" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/ | wc -l
263
+ ```
264
+
265
+ **Memory Management Patterns:**
266
+ ```jsx
267
+ // Proper cleanup implementation
268
+ function ComponentWithCleanup() {
269
+ const [data, setData] = useState(null);
270
+
271
+ useEffect(() => {
272
+ // Event listeners
273
+ const handleScroll = () => {
274
+ console.log('Scrolled');
275
+ };
276
+
277
+ const handleResize = debounce(() => {
278
+ console.log('Resized');
279
+ }, 100);
280
+
281
+ // Timers
282
+ const interval = setInterval(() => {
283
+ fetchLatestData().then(setData);
284
+ }, 5000);
285
+
286
+ // Async operations with AbortController
287
+ const controller = new AbortController();
288
+
289
+ fetchInitialData(controller.signal)
290
+ .then(setData)
291
+ .catch(err => {
292
+ if (!err.name === 'AbortError') {
293
+ console.error('Fetch failed:', err);
294
+ }
295
+ });
296
+
297
+ // Add listeners
298
+ window.addEventListener('scroll', handleScroll);
299
+ window.addEventListener('resize', handleResize);
300
+
301
+ // Cleanup function
302
+ return () => {
303
+ clearInterval(interval);
304
+ controller.abort();
305
+ window.removeEventListener('scroll', handleScroll);
306
+ window.removeEventListener('resize', handleResize);
307
+ };
308
+ }, []);
309
+
310
+ return <div>Component content: {data?.title}</div>;
311
+ }
312
+
313
+ // Memory monitoring hook
314
+ function useMemoryMonitor(componentName) {
315
+ useEffect(() => {
316
+ if (!performance.memory) return;
317
+
318
+ const logMemory = () => {
319
+ console.log(`${componentName} memory:`, {
320
+ used: (performance.memory.usedJSHeapSize / 1048576).toFixed(2) + 'MB',
321
+ total: (performance.memory.totalJSHeapSize / 1048576).toFixed(2) + 'MB'
322
+ });
323
+ };
324
+
325
+ const interval = setInterval(logMemory, 10000);
326
+ return () => clearInterval(interval);
327
+ }, [componentName]);
328
+ }
329
+ ```
330
+
331
+ ### Large Data and Virtualization
332
+ **Common Issues:**
333
+ - Slow scrolling performance with large lists
334
+ - Memory exhaustion when rendering 1000+ items
335
+ - Table performance degrading with many rows
336
+ - Search/filter operations causing UI freezes
337
+
338
+ **Diagnosis:**
339
+ ```bash
340
+ # Check for large data rendering patterns
341
+ grep -r -B 2 -A 2 "\.map(" --include="*.jsx" --include="*.tsx" src/ | grep -E "items\.|data\.|list\." | head -5
342
+
343
+ # Look for virtualization libraries
344
+ npm list react-window react-virtualized @tanstack/react-virtual --depth=0 2>/dev/null | grep -E "(window|virtualized|virtual)"
345
+
346
+ # Check for pagination patterns
347
+ grep -r "page\|limit\|offset\|pagination" --include="*.jsx" --include="*.tsx" src/ | head -3
348
+ ```
349
+
350
+ **Virtualization Implementation:**
351
+ ```jsx
352
+ // react-window implementation
353
+ import { FixedSizeList as List } from 'react-window';
354
+
355
+ const VirtualizedList = ({ items }) => {
356
+ const Row = ({ index, style }) => (
357
+ <div style={style}>
358
+ <ItemComponent item={items[index]} />
359
+ </div>
360
+ );
361
+
362
+ return (
363
+ <List
364
+ height={600} // Viewport height
365
+ itemCount={items.length}
366
+ itemSize={80} // Each item height
367
+ overscanCount={5} // Items to render outside viewport
368
+ >
369
+ {Row}
370
+ </List>
371
+ );
372
+ };
373
+
374
+ // Variable size list for complex layouts
375
+ import { VariableSizeList } from 'react-window';
376
+
377
+ const DynamicList = ({ items }) => {
378
+ const getItemSize = useCallback((index) => {
379
+ // Calculate height based on content
380
+ return items[index].isExpanded ? 120 : 60;
381
+ }, [items]);
382
+
383
+ const Row = ({ index, style }) => (
384
+ <div style={style}>
385
+ <ComplexItemComponent item={items[index]} />
386
+ </div>
387
+ );
388
+
389
+ return (
390
+ <VariableSizeList
391
+ height={600}
392
+ itemCount={items.length}
393
+ itemSize={getItemSize}
394
+ overscanCount={3}
395
+ >
396
+ {Row}
397
+ </VariableSizeList>
398
+ );
399
+ };
400
+ ```
401
+
402
+ ### Core Web Vitals Optimization
403
+ **Target Metrics:**
404
+ - **LCP (Largest Contentful Paint)**: <2.5s
405
+ - **FID (First Input Delay)**: <100ms
406
+ - **CLS (Cumulative Layout Shift)**: <0.1
407
+
408
+ **Measurement Setup:**
409
+ ```bash
410
+ # Install web-vitals library
411
+ npm install web-vitals
412
+
413
+ # Check for existing monitoring
414
+ grep -r "web-vitals\|getCLS\|getFID\|getLCP" --include="*.js" --include="*.jsx" --include="*.ts" --include="*.tsx" src/ | wc -l
415
+ ```
416
+
417
+ **Core Web Vitals Implementation:**
418
+ ```jsx
419
+ // Comprehensive Core Web Vitals monitoring
420
+ import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';
421
+
422
+ function setupWebVitalsMonitoring() {
423
+ const sendToAnalytics = (metric) => {
424
+ console.log(metric.name, metric.value, metric.rating);
425
+ // Send to your analytics service
426
+ gtag('event', metric.name, {
427
+ value: Math.round(metric.name === 'CLS' ? metric.value * 1000 : metric.value),
428
+ event_label: metric.id,
429
+ non_interaction: true,
430
+ });
431
+ };
432
+
433
+ getCLS(sendToAnalytics);
434
+ getFID(sendToAnalytics);
435
+ getFCP(sendToAnalytics);
436
+ getLCP(sendToAnalytics);
437
+ getTTFB(sendToAnalytics);
438
+ }
439
+
440
+ // LCP optimization component
441
+ function OptimizedHero({ imageUrl, title }) {
442
+ return (
443
+ <div>
444
+ <img
445
+ src={imageUrl}
446
+ alt={title}
447
+ // Optimize LCP
448
+ fetchpriority="high"
449
+ decoding="async"
450
+ // Prevent CLS
451
+ width={800}
452
+ height={400}
453
+ style={{ width: '100%', height: 'auto' }}
454
+ />
455
+ <h1>{title}</h1>
456
+ </div>
457
+ );
458
+ }
459
+
460
+ // CLS prevention with skeleton screens
461
+ function ContentWithSkeleton({ isLoading, content }) {
462
+ if (isLoading) {
463
+ return (
464
+ <div style={{ height: '200px', backgroundColor: '#f0f0f0' }}>
465
+ <div className="skeleton-line" style={{ height: '20px', marginBottom: '10px' }} />
466
+ <div className="skeleton-line" style={{ height: '20px', marginBottom: '10px' }} />
467
+ <div className="skeleton-line" style={{ height: '20px', width: '60%' }} />
468
+ </div>
469
+ );
470
+ }
471
+
472
+ return <div style={{ minHeight: '200px' }}>{content}</div>;
473
+ }
474
+ ```
475
+
476
+ ### React 18 Concurrent Features
477
+ **When to Use:**
478
+ - Heavy computations blocking UI
479
+ - Search/filter operations on large datasets
480
+ - Non-urgent updates that can be deferred
481
+ - Improving perceived performance
482
+
483
+ **useTransition Implementation:**
484
+ ```jsx
485
+ import { useTransition, useState, useMemo } from 'react';
486
+
487
+ function SearchResults() {
488
+ const [isPending, startTransition] = useTransition();
489
+ const [query, setQuery] = useState('');
490
+ const [results, setResults] = useState([]);
491
+
492
+ const handleSearch = (newQuery) => {
493
+ // Urgent update - immediate UI feedback
494
+ setQuery(newQuery);
495
+
496
+ // Non-urgent update - can be interrupted
497
+ startTransition(() => {
498
+ const filtered = expensiveSearchOperation(data, newQuery);
499
+ setResults(filtered);
500
+ });
501
+ };
502
+
503
+ return (
504
+ <div>
505
+ <input
506
+ value={query}
507
+ onChange={(e) => handleSearch(e.target.value)}
508
+ placeholder="Search..."
509
+ />
510
+ {isPending && <div>Searching...</div>}
511
+ <ResultsList results={results} />
512
+ </div>
513
+ );
514
+ }
515
+
516
+ // useDeferredValue for expensive renders
517
+ function FilteredList({ filter, items }) {
518
+ const deferredFilter = useDeferredValue(filter);
519
+
520
+ const filteredItems = useMemo(() => {
521
+ // This expensive calculation uses deferred value
522
+ return items.filter(item =>
523
+ item.name.toLowerCase().includes(deferredFilter.toLowerCase())
524
+ );
525
+ }, [items, deferredFilter]);
526
+
527
+ const isStale = filter !== deferredFilter;
528
+
529
+ return (
530
+ <div style={{ opacity: isStale ? 0.5 : 1 }}>
531
+ {filteredItems.map(item =>
532
+ <Item key={item.id} {...item} />
533
+ )}
534
+ </div>
535
+ );
536
+ }
537
+ ```
538
+
539
+ ### Context Performance Optimization
540
+ **Common Issues:**
541
+ - Context changes causing wide re-renders
542
+ - Single large context for entire application
543
+ - Context value recreated on every render
544
+ - Frequent context updates causing performance lag
545
+
546
+ **Context Optimization Patterns:**
547
+ ```jsx
548
+ // ❌ Bad - Single large context
549
+ const AppContext = createContext({
550
+ user: null,
551
+ theme: 'light',
552
+ notifications: [],
553
+ settings: {},
554
+ currentPage: 'home'
555
+ });
556
+
557
+ // ✅ Good - Separate contexts by concern
558
+ const UserContext = createContext(null);
559
+ const ThemeContext = createContext('light');
560
+ const NotificationContext = createContext([]);
561
+
562
+ // Context value memoization
563
+ function AppProvider({ children }) {
564
+ const [user, setUser] = useState(null);
565
+ const [theme, setTheme] = useState('light');
566
+
567
+ // Memoize context value to prevent unnecessary re-renders
568
+ const userContextValue = useMemo(() => ({
569
+ user,
570
+ setUser,
571
+ login: (credentials) => loginUser(credentials).then(setUser),
572
+ logout: () => logoutUser().then(() => setUser(null))
573
+ }), [user]);
574
+
575
+ const themeContextValue = useMemo(() => ({
576
+ theme,
577
+ setTheme,
578
+ toggleTheme: () => setTheme(prev => prev === 'light' ? 'dark' : 'light')
579
+ }), [theme]);
580
+
581
+ return (
582
+ <UserContext.Provider value={userContextValue}>
583
+ <ThemeContext.Provider value={themeContextValue}>
584
+ {children}
585
+ </ThemeContext.Provider>
586
+ </UserContext.Provider>
587
+ );
588
+ }
589
+
590
+ // Context selector pattern for fine-grained updates
591
+ function useUserContext(selector) {
592
+ const context = useContext(UserContext);
593
+ if (!context) {
594
+ throw new Error('useUserContext must be used within UserProvider');
595
+ }
596
+
597
+ return useMemo(() => selector(context), [context, selector]);
598
+ }
599
+
600
+ // Usage with selector
601
+ function UserProfile() {
602
+ const userName = useUserContext(ctx => ctx.user?.name);
603
+ const isLoggedIn = useUserContext(ctx => !!ctx.user);
604
+
605
+ return (
606
+ <div>
607
+ {isLoggedIn ? `Welcome ${userName}` : 'Please log in'}
608
+ </div>
609
+ );
610
+ }
611
+ ```
612
+
613
+ ## Performance Issue Matrix (25 Scenarios)
614
+
615
+ ### Component Optimization Issues
616
+ 1. **Excessive re-renders in DevTools** → Missing React.memo → Add React.memo with custom comparison
617
+ 2. **Child components re-render unnecessarily** → Inline props/functions → Extract stable references with useCallback
618
+ 3. **Slow typing in inputs** → Expensive render calculations → Move to useMemo, use useTransition
619
+ 4. **Context changes cause wide re-renders** → Large single context → Split into focused contexts
620
+ 5. **useState cascade re-renders** → Poor state architecture → Use useReducer, state colocation
621
+
622
+ ### Bundle Optimization Issues
623
+ 6. **Large initial bundle (>2MB)** → No code splitting → Implement React.lazy route splitting
624
+ 7. **Third-party libraries bloating bundle** → Full library imports → Use specific imports, lighter alternatives
625
+ 8. **Slow page load with unused code** → Poor tree-shaking → Fix imports, configure webpack sideEffects
626
+ 9. **Heavy CSS-in-JS performance** → Runtime CSS generation → Extract static styles, use CSS variables
627
+
628
+ ### Memory Management Issues
629
+ 10. **Memory usage grows over time** → Missing cleanup → Add useEffect cleanup functions
630
+ 11. **Browser unresponsive with large lists** → Too many DOM elements → Implement react-window virtualization
631
+ 12. **Memory leaks in development** → Timers not cleared → Use AbortController, proper cleanup
632
+
633
+ ### Large Data Handling Issues
634
+ 13. **Janky scroll performance** → Large list rendering → Implement FixedSizeList virtualization
635
+ 14. **Table with 1000+ rows slow** → DOM manipulation overhead → Add virtual scrolling with pagination
636
+ 15. **Search/filter causes UI freeze** → Synchronous filtering → Use debounced useTransition filtering
637
+
638
+ ### Core Web Vitals Issues
639
+ 16. **Poor Lighthouse score (<50)** → Multiple optimizations needed → Image lazy loading, resource hints, bundle optimization
640
+ 17. **High CLS (>0.1)** → Content loading without dimensions → Set explicit dimensions, skeleton screens
641
+ 18. **Slow FCP (>2s)** → Blocking resources → Critical CSS inlining, resource preloading
642
+
643
+ ### Asset Optimization Issues
644
+ 19. **Images loading slowly** → Unoptimized images → Implement next/image, responsive sizes, modern formats
645
+ 20. **Fonts causing layout shift** → Missing font fallbacks → Add font-display: swap, system fallbacks
646
+ 21. **Animation jank (not 60fps)** → Layout-triggering animations → Use CSS transforms, GPU acceleration
647
+
648
+ ### Concurrent Features Issues
649
+ 22. **UI unresponsive during updates** → Blocking main thread → Use startTransition for heavy operations
650
+ 23. **Search results update too eagerly** → Every keystroke triggers work → Use useDeferredValue with debouncing
651
+ 24. **Suspense boundaries poor UX** → Improper boundary placement → Optimize boundary granularity, progressive enhancement
652
+
653
+ ### Advanced Performance Issues
654
+ 25. **Production performance monitoring missing** → No runtime insights → Implement Profiler components, Core Web Vitals tracking
655
+
656
+ ## Diagnostic Commands
657
+
658
+ ### Bundle Analysis
659
+ ```bash
660
+ # Webpack Bundle Analyzer
661
+ npx webpack-bundle-analyzer build/static/js/*.js --no-open --report bundle-report.html
662
+
663
+ # Next.js Bundle Analysis
664
+ ANALYZE=true npm run build
665
+
666
+ # Vite Bundle Analysis
667
+ npm run build -- --mode analyze
668
+
669
+ # Manual bundle inspection
670
+ ls -lah build/static/js/ | sort -k5 -hr
671
+ ```
672
+
673
+ ### Performance Profiling
674
+ ```bash
675
+ # Lighthouse performance audit
676
+ npx lighthouse http://localhost:3000 --only-categories=performance --view
677
+
678
+ # Chrome DevTools performance
679
+ echo "Use Chrome DevTools > Performance tab to record and analyze runtime performance"
680
+
681
+ # React DevTools profiler
682
+ echo "Use React DevTools browser extension > Profiler tab for React-specific insights"
683
+ ```
684
+
685
+ ### Memory Analysis
686
+ ```bash
687
+ # Node.js memory debugging
688
+ node --inspect --max-old-space-size=4096 scripts/build.js
689
+
690
+ # Memory usage monitoring in browser
691
+ echo "Use performance.memory API and Chrome DevTools > Memory tab"
692
+ ```
693
+
694
+ ## Validation Strategy
695
+
696
+ ### Performance Benchmarks
697
+ - **Component render time**: <16ms per component for 60fps
698
+ - **Bundle size**: Initial load <1MB, total <3MB
699
+ - **Memory usage**: Stable over time, no growth >10MB/hour
700
+ - **Core Web Vitals**: LCP <2.5s, FID <100ms, CLS <0.1
701
+
702
+ ### Testing Approach
703
+ ```bash
704
+ # Performance regression testing
705
+ npm test -- --coverage --watchAll=false --testPathPattern=performance
706
+
707
+ # Bundle size tracking
708
+ npm run build && ls -lah build/static/js/*.js | awk '{sum += $5} END {print "Total bundle:", sum/1024/1024 "MB"}'
709
+
710
+ # Memory leak detection
711
+ echo "Run app for 30+ minutes with typical usage patterns, monitor memory in DevTools"
712
+ ```
713
+
714
+ ### Production Monitoring
715
+ ```jsx
716
+ // Runtime performance monitoring
717
+ function AppWithMonitoring() {
718
+ const onRender = (id, phase, actualDuration, baseDuration, startTime, commitTime) => {
719
+ // Alert on slow renders
720
+ if (actualDuration > 16) {
721
+ analytics.track('slow_render', {
722
+ componentId: id,
723
+ phase,
724
+ duration: actualDuration,
725
+ timestamp: commitTime
726
+ });
727
+ }
728
+ };
729
+
730
+ return (
731
+ <Profiler id="App" onRender={onRender}>
732
+ <App />
733
+ </Profiler>
734
+ );
735
+ }
736
+ ```
737
+
738
+ ## Resources
739
+
740
+ ### Official Documentation
741
+ - [React Performance](https://react.dev/learn/render-and-commit)
742
+ - [React DevTools Profiler](https://react.dev/blog/2018/09/10/introducing-the-react-profiler)
743
+ - [Code Splitting](https://react.dev/reference/react/lazy)
744
+ - [Concurrent Features](https://react.dev/blog/2022/03/29/react-v18)
745
+
746
+ ### Performance Tools
747
+ - [web-vitals](https://web.dev/vitals/)
748
+ - [Lighthouse](https://developers.google.com/web/tools/lighthouse)
749
+ - [react-window](https://react-window.vercel.app/)
750
+ - [webpack-bundle-analyzer](https://github.com/webpack-contrib/webpack-bundle-analyzer)
751
+
752
+ ### Best Practices
753
+ - Profile first, optimize second - measure before and after changes
754
+ - Focus on user-perceived performance, not just technical metrics
755
+ - Use React 18 concurrent features for better user experience
756
+ - Monitor performance in production, not just development
757
+
758
+ ## Code Review Checklist
759
+
760
+ When reviewing React performance code, focus on:
761
+
762
+ ### Component Optimization & Re-renders
763
+ - [ ] Components use React.memo when appropriate to prevent unnecessary re-renders
764
+ - [ ] useCallback is applied to event handlers passed to child components
765
+ - [ ] useMemo is used for expensive calculations, not every computed value
766
+ - [ ] Dependency arrays in hooks are optimized and stable
767
+ - [ ] Inline objects and functions in JSX props are avoided
768
+ - [ ] Component tree structure minimizes prop drilling and context usage
769
+
770
+ ### Bundle Size & Code Splitting
771
+ - [ ] Route-based code splitting is implemented with React.lazy and Suspense
772
+ - [ ] Heavy third-party libraries are loaded dynamically when needed
773
+ - [ ] Bundle analysis shows reasonable chunk sizes (< 1MB initial)
774
+ - [ ] Tree-shaking is working effectively (no unused exports in bundles)
775
+ - [ ] Dynamic imports are used for conditional feature loading
776
+ - [ ] Polyfills and vendor chunks are separated appropriately
777
+
778
+ ### Memory Management & Cleanup
779
+ - [ ] useEffect hooks include proper cleanup functions for subscriptions
780
+ - [ ] Event listeners are removed in cleanup functions
781
+ - [ ] Timers and intervals are cleared when components unmount
782
+ - [ ] Large objects are not held in closures unnecessarily
783
+ - [ ] Memory usage remains stable during extended application use
784
+ - [ ] Component instances are garbage collected properly
785
+
786
+ ### Data Handling & Virtualization
787
+ - [ ] Large lists use virtualization (react-window or similar)
788
+ - [ ] Data fetching includes pagination for large datasets
789
+ - [ ] Infinite scrolling is implemented efficiently
790
+ - [ ] Search and filter operations don't block the UI
791
+ - [ ] Data transformations are memoized appropriately
792
+ - [ ] API responses include only necessary data fields
793
+
794
+ ### Core Web Vitals & User Experience
795
+ - [ ] Largest Contentful Paint (LCP) is under 2.5 seconds
796
+ - [ ] First Input Delay (FID) is under 100 milliseconds
797
+ - [ ] Cumulative Layout Shift (CLS) is under 0.1
798
+ - [ ] Images are optimized and served in modern formats
799
+ - [ ] Critical resources are preloaded appropriately
800
+ - [ ] Loading states provide good user feedback
801
+
802
+ ### React 18 Concurrent Features
803
+ - [ ] useTransition is used for non-urgent state updates
804
+ - [ ] useDeferredValue handles expensive re-renders appropriately
805
+ - [ ] Suspense boundaries are placed strategically
806
+ - [ ] startTransition wraps heavy operations that can be interrupted
807
+ - [ ] Concurrent rendering improves perceived performance
808
+ - [ ] Error boundaries handle async component failures
809
+
810
+ ### Production Monitoring & Validation
811
+ - [ ] Performance metrics are collected in production
812
+ - [ ] Slow renders are detected and tracked
813
+ - [ ] Bundle size is monitored and alerts on regressions
814
+ - [ ] Real user monitoring captures actual performance data
815
+ - [ ] Performance budgets are defined and enforced
816
+ - [ ] Profiling data helps identify optimization opportunities