Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Important
Security Advisory: React2Shell & two new vulnerabilities
Find out more
Pages RouterGuidesLazy Loading

How to lazy load Client Components and libraries

Last updated April 24, 2025

Lazy loading in Next.js helps improve the initial loading performance of an application by decreasing the amount of JavaScript needed to render a route.

next/dynamic

next/dynamic is a composite ofReact.lazy() andSuspense. It behaves the same way in theapp andpages directories to allow for incremental migration.

In the example below, by usingnext/dynamic, the header component will not be included in the page's initial JavaScript bundle. The page will render the Suspensefallback first, followed by theHeader component when theSuspense boundary is resolved.

import dynamicfrom'next/dynamic'constDynamicHeader=dynamic(()=>import('../components/header'), {loading: ()=> <p>Loading...</p>,})exportdefaultfunctionHome() {return <DynamicHeader />}

Good to know: Inimport('path/to/component'), the path must be explicitly written. It can't be a template string nor a variable. Furthermore theimport() has to be inside thedynamic() call for Next.js to be able to match webpack bundles / module ids to the specificdynamic() call and preload them before rendering.dynamic() can't be used inside of React rendering as it needs to be marked in the top level of the module for preloading to work, similar toReact.lazy.

Examples

With named exports

To dynamically import a named export, you can return it from thePromise returned byimport():

components/hello.js
exportfunctionHello() {return <p>Hello!</p>}// pages/index.jsimport dynamicfrom'next/dynamic'constDynamicComponent=dynamic(()=>import('../components/hello').then((mod)=>mod.Hello))

With no SSR

To dynamically load a component on the client side, you can use thessr option to disable server-rendering. This is useful if an external dependency or component relies on browser APIs likewindow.

'use client'import dynamicfrom'next/dynamic'constDynamicHeader=dynamic(()=>import('../components/header'), {  ssr:false,})

With external libraries

This example uses the external libraryfuse.js for fuzzy search. The module is only loaded in the browser after the user types in the search input.

import { useState }from'react'constnames= ['Tim','Joe','Bel','Lee']exportdefaultfunctionPage() {const [results,setResults]=useState()return (    <div>      <inputtype="text"placeholder="Search"onChange={async (e)=> {const {value }=e.currentTarget// Dynamically load fuse.jsconstFuse= (awaitimport('fuse.js')).defaultconstfuse=newFuse(names)setResults(fuse.search(value))        }}      />      <pre>Results: {JSON.stringify(results,null,2)}</pre>    </div>  )}

Was this helpful?

supported.

[8]ページ先頭

©2009-2025 Movatter.jp