Code Splitting in Next.js using Dynamic Imported Routes
Split code at the router level by dynamically importing Next.js pages, ensuring that only the necessary code is loaded per route.
import dynamic from 'next/dynamic';
// Dynamic import of a component
const DynamicComponent = dynamic(() => import('../components/MyComponent'));
function HomePage() {
// Use the dynamically imported component inside your component
return (
<div>
<h1>Welcome to the home page!</h1>
<DynamicComponent />
</div>
);
}
export default HomePage;
This code snippet shows how to dynamically import a component in Next.js. The 'dynamic' function from Next.js is used to import 'MyComponent' only when it's needed (when the 'HomePage' component is rendered).
import dynamic from 'next/dynamic';
// Dynamic import of a Next.js page
const DynamicPage = dynamic(() => import('../pages/SomePage'));
// A standard Next.js component
function LinkToDynamicPage() {
// This will be a link or button that when clicked,
// loads the dynamic page
return (
<div>
<h1>Click to load the dynamic page</h1>
<button onClick={() => DynamicPage()}>
Load Dynamic Page
</button>
</div>
);
}
export default LinkToDynamicPage;
This code example shows how to set up an on-demand loading for a Next.js page using the 'dynamic' function. 'DynamicPage' is a placeholder that will only load the 'SomePage' component from the pages directory when the user interacts with the LinkToDynamicPage component, such as clicking a button.