12 min read
ā¢Question 36 of 47hardNext.js Performance Optimization
Advanced performance optimization techniques.
Performance Optimization
Bundle Analysis
$ terminalBash
# Install analyzer
npm install @next/bundle-analyzer
# next.config.js
const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true',
});
module.exports = withBundleAnalyzer({});
# Run analysis
ANALYZE=true npm run buildCode Splitting Strategies
code.txtTSX
// Dynamic imports with loading states
import dynamic from 'next/dynamic';
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <Skeleton />,
ssr: false, // Client-only
});
// Named exports
const Chart = dynamic(
() => import('./charts').then((mod) => mod.LineChart),
{ loading: () => <ChartSkeleton /> }
);Image Optimization
code.txtTSX
import Image from 'next/image';
// Optimized with priority for LCP
<Image
src="/hero.jpg"
width={1200}
height={600}
priority // Preload for LCP
placeholder="blur"
blurDataURL={blurHash}
sizes="(max-width: 768px) 100vw, 50vw"
/>
// Lazy load below fold
<Image
src="/feature.jpg"
width={600}
height={400}
loading="lazy"
/>Font Optimization
code.txtTSX
import { Inter, Roboto_Mono } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
display: 'swap',
variable: '--font-inter',
});
export default function RootLayout({ children }) {
return (
<html className={inter.variable}>
<body>{children}</body>
</html>
);
}Core Web Vitals
code.txtTSX
// Track CWV
export function reportWebVitals(metric) {
switch (metric.name) {
case 'LCP':
case 'FID':
case 'CLS':
analytics.track(metric.name, metric.value);
}
}