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