Lazy Loading
Lazy load imported libraries and React Components to improve your application's loading performance.
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.
It allows you to defer loading of Client Components and imported libraries, and only include them in the client bundle when they're needed. For example, you might want to defer loading a modal until a user clicks to open it.
There are two ways you can implement lazy loading in Next.js:
- Using Dynamic Imports with
next/dynamic
- Using
React.lazy()
with Suspense
By default, Server Components are automatically code split, and you can use streaming to progressively send pieces of UI from the server to the client. Lazy loading applies to Client Components.
next/dynamic
next/dynamic
is a composite of React.lazy()
and Suspense. It behaves the same way in the app
and pages
directories to allow for incremental migration.
Examples
Importing Client Components
Skipping SSR
When using React.lazy()
and Suspense, Client Components will be prerendered (SSR) by default.
Note: ssr: false
option will only work for client components, move it into client components ensure the client code-splitting working properly.
If you want to disable pre-rendering for a Client Component, you can use the ssr
option set to false
:
Importing Server Components
If you dynamically import a Server Component, only the Client Components that are children of the Server Component will be lazy-loaded - not the Server Component itself. It will also help preload the static assets such as CSS when you're using it in Server Components.
Note: ssr: false
option is not supported in Server Components. You will see an error if you try to use it in Server Components.
ssr: false
is not allowed with next/dynamic
in Server Components. Please move it into a client component.
Loading External Libraries
External libraries can be loaded on demand using the import()
function. This example uses the external library fuse.js
for fuzzy search. The module is only loaded on the client after the user types in the search input.
Adding a custom loading component
Importing Named Exports
To dynamically import a named export, you can return it from the Promise returned by import()
function: