Lazy loading is a performance optimization technique where resources (like images, components, or routes) are loaded only when needed, rather than at the initial page load.
In Next.js, you can lazy load images, components, and even pages. Here’s how each works:
š¼ļø 1. Lazy Loading Images (Built-in)
Use the Next.js <Image />
component from next/image
:
import Image from 'next/image';
export default function Home() {
return (
<Image
src="/hero.jpg"
alt="Hero Banner"
width={800}
height={600}
priority={false} // false = lazy loaded
/>
);
}
ā
Automatically lazy loads by default (unless you use priority={true}
).
š§© 2. Lazy Loading Components with next/dynamic
Use dynamic()
to import a component only when it’s needed (e.g., after the page loads):
import dynamic from 'next/dynamic';
const LazyComponent = dynamic(() => import('../components/HeavyComponent'), {
loading: () => <p>Loading...</p>, // Optional fallback
ssr: false, // Optional: disables SSR if needed
});
export default function Page() {
return (
<div>
<h1>My Page</h1>
<LazyComponent />
</div>
);
}
ā Useful for reducing initial JS bundle size.
š§ 3. Lazy Loading Routes (via Dynamic Imports)
In large apps, especially SPAs, you can lazy load route-level components:
const BlogPage = dynamic(() => import('../pages/blog'));
Note: With Next.js, routing is generally handled by the file system, so this is rarely necessary unless you’re manually rendering a page component inside another.
ā Benefits of Lazy Loading
ā” Faster initial page load
š Reduced bundle size
šÆ Loads content as the user interacts or scrolls
Want a real example of lazy loading in a Next.js project (like loading a video player or chart component only when visible)?