Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Next.js Tutorial
  • Next.js Components
  • Next.js Functions
  • Next.js Deployment
  • Next.js Projects
  • Next.js Routing
  • Next.js Styles
  • Next.js Server-Side Rendering
  • Next.js Environment Variables
  • Next.js Middleware
  • Next.js Typescript
  • Next.js Image Optimization
  • Next.js Data Fetching
Open In App
Next Article:
Next.js Dynamic Import
Next article icon

Next.js Dynamic Import

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Unlike standard import modules, dynamic import modules are flexible in terms of when and how they are loaded. Instead of being forced to upload a module file during reading, a powerful import can be requested during use. With code separating the module into a separate batch file it can be downloaded separately which reduces the load on the first page.

Dynamic Imports

Next.js Dynamic Import allows loading components, pages, or modules asynchronously based on user interactions or conditions, optimizing performance by loading resources only when needed, enhancing application efficiency and user experience.

Syntax:

import dynamic from 'next/dynamic';

const dynamicComp = dynamic(() => import("path_to_dynamicComponent"));

Set Up Dynamic Imports in Next.js

Before you proceed, there are some things you should be aware of about the dynamic import. Although dynamic import 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 React Application

Step 1: Create a React application using the following command and move to that folder:

npx create-next-app gfg
cd gfg

Step 2: Create components named folder in your root directory. Create a folder named components. Run the command to create a 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
// components/GFG.js  import React from "react";  function GFG() {     return (         <div>             <h1>Welcome TO GeeksforGeeks</h1>         </div>     ); }  export default GFG; 
JavaScript
// Filename - components/Hello.js  import React from "react";  function Hello() {     return (         <div>             <h1>Hello Geeks</h1>         </div>     ); }  export default Hello; 

Project Structure: Your project directory will look like this:

p1

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

In your directory, you can see a pages folder inside that index.js file will be there. import dynamic from 'next/dynamic'. And make state and button to show those two components and working of dynamic as well as benefits.

JavaScript
// Filename - pages/index.js   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:


Next Article
Next.js Dynamic Import

K

krcpr007
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • ReactJS
  • Geeks Premier League
  • Geeks-Premier-League-2022
  • Next.js

Similar Reads

    How to import image in Next.js ?
    Next.js is a full-stack React-based framework. Unlike a traditional react app, which loads and renders the entire application on the client, Next.js allows the first-page load to be rendered by the server, which is great for SEO and performance. Some of the key features of Next.js are:  Server-side
    4 min read
    Next JS Dynamic API Routes
    Next.js dynamic API routes allow you to create flexible endpoints that can handle various parameters, enabling powerful and versatile server-side functionalities within your application.Prerequisites:JavaScript and React JS basicsFamiliar with Next JSRestful API's conceptDynamic API RoutesDynamic AP
    2 min read
    Next.js src Directory
    The NextJS src directory is a project structure that is optional but is widely recommended. It helps to organize the project in a well-defined structure.Organizing a Next.js project with a well-planned folder structure is important for readability, scalability, and maintainability. A clear structure
    4 min read
    Dynamic Import Expressions in TypeScript
    TypeScript, a superset of JavaScript, brings static typing to JavaScript, which enhances code quality and maintainability. One of the powerful features supported in TypeScript and modern JavaScript is the ability to conditionally or lazily load modules using dynamic import expressions. This feature
    3 min read
    Next.js Script Component
    The Next.js Script component helps you manage when and how scripts are loaded to make your site perform better. It offers three strategies: beforeInteractive for scripts that need to load immediately, afterInteractive for scripts that are needed after the page becomes interactive but aren’t crucial
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences