Performance Monitoring & Optimization
Measure and optimize React performance: React DevTools Profiler, Web Vitals, bundle analysis, Core Web Vitals, performance budgets, real user monitoring (RUM), and optimization strategies used in production.
🔬 1. React DevTools Profiler
Time to put on your detective hat! 🕵️ The React Profiler is your magnifying glass for finding performance villains lurking in your component tree. Track render times, spot unnecessary re-renders, and catch those sneaky bottlenecks before your users even notice them!
🟠 Impact: HIGH — You can't optimize what you can't measure — the Profiler reveals exactly where your renders are wasting time
📋 In this section: Profiler Component • onRender Callback • Performance Hooks • Slow Render Detection
// ✅ Profiler Componentimport { Profiler, ProfilerOnRenderCallback } from 'react';const onRenderCallback: ProfilerOnRenderCallback = (id,phase,actualDuration,baseDuration,startTime,commitTime) => {console.log('Profiler:', {id,phase, // "mount" or "update"actualDuration, // Time spent renderingbaseDuration, // Estimated time without memoizationstartTime,commitTime});// Send to analyticsif (actualDuration > 16) { // > 1 frame at 60fpsperformanceAnalytics.recordSlowRender(id, actualDuration);}};function App() {return (<Profiler id="App" onRender={onRenderCallback}><Header /><Profiler id="ProductList" onRender={onRenderCallback}><ProductList /></Profiler></Profiler>);}// ✅ Performance monitoring hookfunction usePerformanceMonitor(componentName: string) {useEffect(() => {const startTime = performance.now();return () => {const endTime = performance.now();const duration = endTime - startTime;if (duration > 100) {console.warn(`${componentName} took ${duration}ms to render`);}// Send to monitoring serviceanalytics.track('component_render_time', {component: componentName,duration});};});}// Usagefunction ExpensiveComponent() {usePerformanceMonitor('ExpensiveComponent');// Component logic}
📊 2. Web Vitals & Core Web Vitals
Google is watching! 👀 Core Web Vitals (LCP, FID, CLS) directly impact your SEO rankings and user satisfaction. Track them like a hawk and keep your scores green. Your users' experience — and your search rankings — depend on it! 🏆
🔴 Impact: CRITICAL — Core Web Vitals affect SEO rankings AND user experience — poor scores mean lost traffic and unhappy users
📋 In this section: LCP / FID / CLS Tracking • web-vitals Library • Custom Performance Observer • Custom Measurements
// ✅ Web Vitals trackingimport { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';function sendToAnalytics(metric: any) {// Send to your analytics serviceanalytics.track('web_vital', {name: metric.name,value: metric.value,id: metric.id,delta: metric.delta,rating: metric.rating // 'good', 'needs-improvement', or 'poor'});}// Track all Core Web VitalsgetCLS(sendToAnalytics);getFID(sendToAnalytics);getFCP(sendToAnalytics);getLCP(sendToAnalytics);getTTFB(sendToAnalytics);// ✅ Custom performance observerfunction useWebVitals() {useEffect(() => {const observer = new PerformanceObserver((list) => {for (const entry of list.getEntries()) {// Log or send to analyticsconsole.log(entry.name, entry.duration);}});observer.observe({ entryTypes: ['measure', 'navigation'] });return () => observer.disconnect();}, []);}// ✅ Measure custom operationsfunction measurePerformance(name: string, fn: () => void) {performance.mark(`${name}-start`);fn();performance.mark(`${name}-end`);performance.measure(name, `${name}-start`, `${name}-end`);const measure = performance.getEntriesByName(name)[0];console.log(`${name}: ${measure.duration}ms`);}// UsagemeasurePerformance('dataProcessing', () => {processLargeDataset(data);});
📦 3. Bundle Analysis
Your bundle is like a suitcase — pack too much and it won't close! 🧳 Bundle analysis helps you see exactly what's taking up space, find heavy dependencies hiding in node_modules, and decide what to lazy-load. Shrink that bundle and watch your load times plummet! 🚀
🟠 Impact: HIGH — Every KB counts — a bloated bundle means slower loads, higher bounce rates, and frustrated users on slow connections
📋 In this section: webpack-bundle-analyzer • Dynamic Imports • Tree Shaking • CI Bundle Size Monitoring
// ✅ Bundle analysis with webpack-bundle-analyzer// package.json scripts{"scripts": {"analyze": "ANALYZE=true npm run build","build": "next build"}}// next.config.jsconst withBundleAnalyzer = require('@next/bundle-analyzer')({enabled: process.env.ANALYZE === 'true'});module.exports = withBundleAnalyzer({// Your config});// ✅ Dynamic imports for code splittingimport dynamic from 'next/dynamic';// Lazy load heavy componentsconst HeavyChart = dynamic(() => import('./HeavyChart'), {loading: () => <ChartSkeleton />,ssr: false});// ✅ Tree shaking optimization// Use named exports instead of default exportsexport { ComponentA, ComponentB }; // ✅ Goodexport default ComponentA; // ❌ Bad for tree shaking// ✅ Analyze import costsfunction useImportCost() {useEffect(() => {// Use tools like import-cost extension// Or analyze in build time}, []);}// ✅ Monitor bundle size in CI// .github/workflows/bundle-size.yml// name: Bundle Size// on: [pull_request]// jobs:// analyze:// runs-on: ubuntu-latest// steps:// - uses: actions/checkout@v2// - run: npm ci// - run: npm run build// - uses: preactjs/compressed-size-action@v2