Next.js Dynamic Import

Last Updated : 9 Jul, 2026

It allows components or modules to be loaded only when they are needed, instead of loading everything during the initial page load. This improves performance by reducing the initial bundle size.

  • Loads components asynchronously (on demand) to optimize performance.
  • Helps in code splitting, reducing the initial JavaScript bundle size.
  • Improves page load speed and user experience by loading resources only when required.

Syntax

import dynamic from 'next/dynamic';
const dynamicComp = dynamic(() => import("./Component"));

Set Up Dynamic Imports in Next.js

Before you proceed, there are some things you should be aware of about dynamic imports. Although dynamic imports can reduce page load, it is very important to know how the bulk download process behaves in order to avoid negative consequences that may increase page load.

  • Dynamic imports are fetched when the component is rendered for the first time.
  • Already rendered imports do not trigger an additional re-fetch.
  • Each dynamic import will create a newly incremented bundle file. This includes nested dynamic imports.
  • Each dynamic import adds a new server request.

Creating Next.js Application

Step 1: Create a new next.js application using the following command:

npx create-next-app@latest my-next-app
cd my-next-app

Step 2: Create a components folder inside the src directory. Then create two files named GFG.js and Hello.js inside the components folder.

mkdir components 

Step 3: Inside the folder create two files. Inside the component folder, the two javascript files are named GFG.js and Hello.js with the following code.

JavaScript
// Filename - src/components/GFG.js
export default function GFG() {
  return (
    <div>
      <h1>Welcome to GeeksforGeeks</h1>
    </div>
  );
}
JavaScript
// Filename - src/components/Hello.js
export default function Hello() {
  return (
    <div>
      <h1>Hello Geeks</h1>
    </div>
  );
}

Project Structure: Your project directory will look like this:

Screenshot-2026-07-01-182849

Step 4: Inside index.js we have import dynamic. 

Open the src/app/page.js file and import the dynamic function from next/dynamic. Then use useState to toggle between the Hello and GFG components.

JavaScript
// Filename - src/app/page.js 
"use client";
import dynamic from "next/dynamic";
import { useState } from "react";
import Hello from "../components/Hello";
export default function Home() {
    const [showComp, SetShowComp] = useState(false);
    const GFG = dynamic(() => import("../components/GFG"));
    return (
        <div>
            {showComp ? <GFG /> : <Hello />}
            <button onClick={() => SetShowComp(!showComp)}>
                Toggle Component
            </button>
        </div>
    );
}

Step to run the application: Run the application using the following command:

npm start

Output:

Comment

Explore