In Next.js, the next/dynamic
module is used to dynamically import a component or module, allowing for code splitting. Code splitting is a technique that enables a web application to load only the necessary code for the current page, improving performance by reducing the initial bundle size.
Here’s a basic example of how next/dynamic
can be used:
// ExampleComponent.js
const ExampleComponent = () => {
return <div>This is a dynamically imported component.</div>;
};
export default ExampleComponent;
Now, let’s use next/dynamic
to dynamically import ExampleComponent
in another file:
// SomePage.js
import dynamic from 'next/dynamic';
const DynamicExampleComponent = dynamic(() => import('../components/ExampleComponent'), {
loading: () => <p>Loading...</p>,
ssr: false, // Set to false to disable server-side rendering for this component
});
const SomePage = () => {
return (
<div>
<p>This is a regular component on the page.</p>
<DynamicExampleComponent />
</div>
);
};
export default SomePage;
In this example, DynamicExampleComponent
is a dynamically imported version of ExampleComponent
. The import('../components/ExampleComponent')
statement is wrapped inside the dynamic
function. The loading
prop is optional and allows you to provide a loading indicator or placeholder while the component is being loaded.
The ssr
(server-side rendering) prop is set to false
in this example. This means that the component will be loaded only on the client side and won't be part of the initial server-side rendered content. This can be useful for components that are not needed during the initial render or if they depend on client-side functionality.
Using next/dynamic
for code splitting can help optimize the performance of your Next.js application by loading only the necessary code when it's required.
Thanks for reading!
Check out original article published here : https://codeymaze.com