Next.js Performance

Performance Budget

Bundle analysis, code splitting, tree shaking, and Core Web Vitals.

Advertisement

Performance Budget

Bundle analysis, code splitting, tree shaking, and Core Web Vitals.

Overview

Performance budgets ensure fast load times and good user experience.

Key Concepts

  • Bundle Analysis — Visualize bundle composition
  • Code Splitting — Load code on demand
  • Tree Shaking — Remove unused code
  • Core Web Vitals — FCP, LCP, CLS, FID metrics
  • Performance Monitoring — Track real user metrics

Code Examples

// next.config.js
module.exports = {
  experimental: {
    optimizePackageImports: ['@mui/material', '@mui/icons-material', 'lodash']
  }
};

// Dynamic imports for code splitting
import dynamic from 'next/dynamic';

const HeavyChart = dynamic(() => import('../components/HeavyChart'), {
  loading: () => <div className="h-64 bg-gray-100 animate-pulse" />,
  ssr: false
});

// Performance monitoring
'use client';
import { useEffect } from 'react';

export function PerformanceMonitor() {
  useEffect(() => {
    if (typeof window !== 'undefined') {
      import('web-vitals').then(({ onCLS, onFID, onLCP, onFCP }) => {
        onCLS(console.log);
        onFID(console.log);
        onLCP(console.log);
        onFCP(console.log);
      });
    }
  }, []);

  return null;
}

// Lazy load below the fold
function BelowFold() {
  const [isVisible, setIsVisible] = useState(false);
  const ref = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting) {
          setIsVisible(true);
          observer.disconnect();
        }
      },
      { threshold: 0.1 }
    );
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, []);

  return (
    <div ref={ref}>
      {isVisible ? <HeavyComponent /> : <Placeholder />}
    </div>
  );
}

Practice

Analyze and optimize a Next.js app's bundle size and Core Web Vitals.