How to use Dynamic Imports with next/dynamic In Next.js
next/dynamic
combines the functionalities of both React.lazy() and Suspense. It operates similarly within both the app and pages directories, facilitating gradual migration.
Example: Below is an example of lazy loading using Dynamic Imports with next/dynamic.
// page.js this is the entry point of application
"use client";
import React, { useState } from "react";
import dynamic from "next/dynamic";
const LazyComp = dynamic(() => import("./components/Lazycomp"), {
loading: () => <h1>Loading...</h1>,
});
function Home() {
const [shown, setShown] = useState(false);
return (
<div style={{ margin: "30px" }}>
<p> w3wiki lazy loading article in nextjs app</p>
<button
style={{
background: "green", color: "white"
}}
onClick={() => setShown(!shown)}
>
Load Component
</button>
{shown && <LazyComp />}
</div>
);
}
export default Home;
//lazy Component that render dynamically
function Lazycomp() {
return (
<div style={{ margin: "30px" }}>
Lazy loading in Next.js is a technique used to improve the performance and
loading times of web applications built with the Next.js framework. With
lazy loading, components or modules are loaded only when they are needed,
rather than upfront when the page is initially rendered. This means that
resources are fetched asynchronously, allowing the initial page load to be
faster and reducing the overall bandwidth usage. Next.js provides built-in
support for lazy loading through dynamic imports, allowing developers to
split their code into smaller chunks and load them on demand. By
implementing lazy loading, Next.js applications can deliver a smoother and
more responsive user experience, particularly for larger applications with
complex component hierarchies.
</div>
);
}
export default Lazycomp;
Start your application using the following command.
npm run dev
Output:
Lazy Loading in Next.js
Lazy loading in NextJS is a technique used to improve the performance and loading times of web applications built with the NextJS framework. With lazy loading, components or modules are loaded only when they are needed, rather than upfront when the page is initially rendered.
This means that resources are fetched asynchronously, allowing the initial page load to be faster and reducing the overall bandwidth usage. NextJS provides built-in support for lazy loading through dynamic imports, allowing developers to split their code into smaller chunks and load them on demand.
We will discuss the approach of Lazy Loading in NextJS:
Table of Content
- Using Dynamic Imports with next/dynamic
- Using React.lazy() with Suspense
Prerequisites
Steps to Create a NextJS App:
Step 1: Create a NextJS application.
npx create-next-app <-foldername->
Let’s say, This will be the procedure, with no changes in dependencies.
Step 2: Move to the Project directory
cd <-foldername->