What is code splitting?
Code splitting is a technique that breaks down large JavaScript bundles into smaller, more manageable chunks. These chunks are then loaded on demand, which can significantly improve the initial load time of your application.
How Next.js implements it automatically:
Next.js provides automatic code splitting out of the box. It achieves this through a few key mechanisms:
- Page-based splitting: Each file in the pages directory (or app directory for App Router) becomes its own JavaScript bundle.
- Dynamic imports: Next.js supports dynamic import() statements, which allow you to load modules on demand.
- Prefetching: Next.js automatically prefetches the code for other pages in the background, making navigation feel instant.
Benefits for performance:
- Faster initial load times: Only the code necessary for the current page is loaded initially.
- Improved caching: Smaller, separate chunks can be cached more efficiently.
- Reduced memory usage: Less unused code is kept in memory.
- Faster navigation: Prefetching ensures smooth transitions between pages.
Code Examples:
// pages/index.js
export default function Home() {
return <h1>Welcome to the home page!</h1>
}
// pages/about.js
export default function About() {
return <h1>About us</h1>
}
In this example, Next.js automatically creates separate bundles for the home and about pages. When a user visits the home page, only the code for that page is loaded.
Dynamic imports for component-level code splitting:
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() => import('../components/heavy-component'))
export default function Page() {
return (
<div>
<h1>Page with dynamic import</h1>
<DynamicComponent />
</div>
)
}
Here, HeavyComponent is only loaded when the page renders, not during the initial page load.
Dynamic imports with custom loading component:
import dynamic from 'next/dynamic'
const DynamicComponentWithCustomLoading = dynamic(
() => import('../components/heavy-component'),
{
loading: () => <p>Loading...</p>
}
)
export default function Page() {
return (
<div>
<h1>Page with dynamic import and custom loading</h1>
<DynamicComponentWithCustomLoading />
</div>
)
}
This example shows how to display a custom loading state while the dynamic component is being loaded.