---
title: How to lazy load Client Components and libraries
description: "Lazy load imported libraries and React Components to improve your application's loading performance."
url: "https://nextjs.org/docs/app/guides/lazy-loading"
docs_index: /docs/llms.txt
lastUpdated: 2026-12-01
navTitle: "Lazy Loading"
prerequisites:
  - "Guides: /docs/app/guides"
---

> For an index of all documentation, see [/docs/llms.txt](/docs/llms.txt).

[Lazy loading](https://developer.mozilla.org/docs/Web/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:

1. Using [Dynamic Imports](#nextdynamic) with `next/dynamic`
2. Using [`React.lazy()`](https://react.dev/reference/react/lazy) with [Suspense](https://react.dev/reference/react/Suspense)

By default, Server Components are automatically [code split](https://developer.mozilla.org/docs/Glossary/Code_splitting), and you can use [streaming](/docs/app/guides/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()`](https://react.dev/reference/react/lazy) and [Suspense](https://react.dev/reference/react/Suspense). It behaves the same way in the `app` and `pages` directories to allow for incremental migration.

## Choosing what to lazy load

Next.js already splits Client Component code by route, so a route loads the code for the components it renders. Lazy loading splits code within a route. Use it for UI that is not on screen when the page first loads, such as a modal that opens on a click, so its code is requested separately from the rest of the route.

Each lazy loaded component adds a network request, and requests carry overhead even when the file is small. Lazy load code that is large or that few visitors need, and import small components normally. To learn how Next.js balances the number of requests against download size, see [How Turbopack chunks your JavaScript](https://nextjs.org/blog/turbopack-chunking).

| The component is                                                                                   | Approach                                                                                                                   |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| Visible when the page loads                                                                        | Import it normally, so it is prerendered with the page                                                                     |
| Visible when the page loads, but can only render in the browser                                    | [`use(browser())`](/docs/app/guides/single-page-applications#rendering-components-only-in-the-browser) inside `<Suspense>` |
| Likely to be opened, such as a reply box or the next tab                                           | [Preload it before the interaction](#preloading-before-interaction)                                                        |
| Opened by few visitors, such as a modal or a chat box                                              | [Load it on interaction](#loading-on-interaction)                                                                          |
| Visible when the page loads, and built on a module that reads `window` or `document` when imported | [`next/dynamic` with `ssr: false`](#skipping-ssr)                                                                          |

Whether to preload depends on how often visitors open the component. Use your analytics to decide.

> **Good to know:**
>
> - A component that renders only after an interaction, or from state that exists only in the browser, is not part of prerendering. It stays out of the server render without `use(browser())` or `ssr: false`.
> - To guarantee that a component renders only in the browser, however it is gated, see [Rendering components only in the browser](/docs/app/guides/single-page-applications#rendering-components-only-in-the-browser).
> - With `loading` or `ssr: false`, `next/dynamic` renders its own `<Suspense>` boundary around the component and uses `loading` as the fallback, so you don't add one yourself. React reveals content behind a fallback with its next batch of suspended content, so set these options when you want a placeholder.

## Examples

### Importing Client Components

```jsx title="app/page.js"
'use client'

import { useState } from 'react'
import dynamic from 'next/dynamic'

// Client Components:
const ComponentA = dynamic(() => import('../components/A'))
const ComponentB = dynamic(() => import('../components/B'))
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })

export default function ClientComponentExample() {
  const [showMore, setShowMore] = useState(false)

  return (
    <div>
      {/* Load immediately, but in a separate client bundle */}
      <ComponentA />

      {/* Load on demand, only when/if the condition is met */}
      {showMore && <ComponentB />}
      <button onClick={() => setShowMore(!showMore)}>Toggle</button>

      {/* Load only on the client side */}
      <ComponentC />
    </div>
  )
}
```

> **Note:**
>
> When a Server Component dynamically imports a Client Component, automatic [code splitting](https://developer.mozilla.org/docs/Glossary/Code_splitting) is currently **not** supported.

### Skipping SSR

When using `React.lazy()` and Suspense, Client Components will be [prerendered](https://github.com/reactwg/server-components/discussions/4) (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.

To lazy load a Client Component and skip prerendering it, set the `ssr` option to `false`. Next.js then leaves the component's module out of the server render, which suits libraries that read `window` or `document` when imported:

```jsx
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
```

To render a component only in the browser without lazy loading its code, see [Rendering components only in the browser](/docs/app/guides/single-page-applications#rendering-components-only-in-the-browser).

### 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.

```jsx title="app/page.js"
import dynamic from 'next/dynamic'

// Server Component:
const ServerComponent = dynamic(() => import('../components/ServerComponent'))

export default function ServerComponentExample() {
  return (
    <div>
      <ServerComponent />
    </div>
  )
}
```

> **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()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/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.

```jsx title="app/page.js"
'use client'

import { useState } from 'react'

const names = ['Tim', 'Joe', 'Bel', 'Lee']

export default function Page() {
  const [results, setResults] = useState()

  return (
    <div>
      <input
        type="text"
        placeholder="Search"
        onChange={async (e) => {
          const { value } = e.currentTarget
          // Dynamically load fuse.js
          const Fuse = (await import('fuse.js')).default
          const fuse = new Fuse(names)

          setResults(fuse.search(value))
        }}
      />
      <pre>Results: {JSON.stringify(results, null, 2)}</pre>
    </div>
  )
}
```

### Adding a custom loading component

```jsx title="app/page.js"
'use client'

import dynamic from 'next/dynamic'

const WithCustomLoading = dynamic(
  () => import('../components/WithCustomLoading'),
  {
    loading: () => <p>Loading...</p>,
  }
)

export default function Page() {
  return (
    <div>
      {/* The loading component will be rendered while  <WithCustomLoading/> is loading */}
      <WithCustomLoading />
    </div>
  )
}
```

### Loading on interaction

A component that renders conditionally loads its code the first time it renders, for example when a user opens a chat box. Load it with `next/dynamic` and update state in a [transition](https://react.dev/reference/react/useTransition). React keeps the current UI on screen until the component is ready, and `isPending` lets you show that the click registered:

```jsx title="app/page.js"
'use client'

import { useState, useTransition } from 'react'
import dynamic from 'next/dynamic'

const ChatBox = dynamic(() => import('../components/chat-box'))

export default function Page() {
  const [open, setOpen] = useState(false)
  const [isPending, startTransition] = useTransition()

  return (
    <div>
      <button
        disabled={isPending}
        onClick={() => startTransition(() => setOpen(true))}
      >
        {isPending ? 'Opening…' : 'Open chat'}
      </button>
      {open && <ChatBox />}
    </div>
  )
}
```

Without a transition, the closest `<Suspense>` boundary above the component shows its fallback while the code loads.

> **Good to know:**
>
> Use a transition even when no boundary is above the component today. Without one, a [`loading.js`](/docs/app/api-reference/file-conventions/loading) file or a `<Suspense>` boundary added higher in the tree later replaces the UI it wraps with its fallback when the user opens the component.

The example sets neither `loading` nor `ssr: false`. With either option, `next/dynamic` renders its own `<Suspense>` boundary around the component, with `loading` as the fallback. React shows that fallback right away and reveals the component with its next batch of suspended content. React spaces these reveals apart so content doesn't appear piece by piece, which means the component can show up later than its code loads. See the [Suspense caveats](https://react.dev/reference/react/Suspense#caveats) for the timing.

A component that first renders after an interaction is not part of the server render, so it does not need `ssr: false`, even when it depends on a module that reads `window` or `document` when imported. If the gate can be open during prerendering, the component renders on the server like any other. To keep it out of the server render regardless of the gate, see [Rendering components only in the browser](/docs/app/guides/single-page-applications#rendering-components-only-in-the-browser).

### Preloading before interaction

When a component is likely to be opened, load its code ahead of the interaction so it appears without a wait.

Render the component inside a hidden [`<Activity>`](https://react.dev/reference/react/Activity). React prepares hidden content in the background, which loads the code, and shows the component when `mode` changes to `visible`:

```jsx title="app/page.js"
'use client'

import { Activity, useState } from 'react'
import dynamic from 'next/dynamic'

const ReplyBox = dynamic(() => import('../components/reply-box'))

export default function Page() {
  const [open, setOpen] = useState(false)

  return (
    <div>
      <button onClick={() => setOpen(true)}>Reply</button>
      <Activity mode={open ? 'visible' : 'hidden'}>
        <ReplyBox />
      </Activity>
    </div>
  )
}
```

The code downloads on every visit, shortly after the page hydrates, whether or not the user opens the component.

To download the code only when a user shows intent, start the download when they hover or focus the trigger. Share one loader function between the preload and `next/dynamic`:

```jsx title="app/page.js"
'use client'

import { startTransition, useState } from 'react'
import dynamic from 'next/dynamic'

const loadReplyBox = () => import('../components/reply-box')
const ReplyBox = dynamic(loadReplyBox)

export default function Page() {
  const [open, setOpen] = useState(false)

  return (
    <div>
      <button
        onMouseEnter={loadReplyBox}
        onFocus={loadReplyBox}
        onClick={() => startTransition(() => setOpen(true))}
      >
        Reply
      </button>
      {open && <ReplyBox />}
    </div>
  )
}
```

The same loader can run at other moments, for example shortly after the page loads. Call it from a `setTimeout`, or from [`requestIdleCallback`](https://developer.mozilla.org/docs/Web/API/Window/requestIdleCallback) in browsers that support it.

### Importing Named Exports

To dynamically import a named export, you can return it from the Promise returned by [`import()`](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/import) function:

```jsx title="components/hello.js"
'use client'

export function Hello() {
  return <p>Hello!</p>
}
```

```jsx title="app/page.js"
import dynamic from 'next/dynamic'

const ClientComponent = dynamic(() =>
  import('../components/hello').then((mod) => mod.Hello)
)
```

## Magic Comments

Next.js supports magic comments to control how dynamic imports are handled by the bundler. These comments work with dynamic `import()`, `require()`, `require.resolve()`, and `new Worker()` expressions.

> **Good to know:**
>
> Magic comments do not work with static `import` statements (`import x from 'y'`). They only work with dynamic expressions.

### `webpackIgnore` / `turbopackIgnore`

Use these comments to skip bundling a dynamic import. The import expression will be left as-is in the output, useful for runtime-only modules:

```js
// Skip bundling - import happens at runtime
const runtime = await import(/* webpackIgnore: true */ 'runtime-module')

// Turbopack-specific variant
const plugin = await import(/* turbopackIgnore: true */ pluginPath)

// Also works with require
const mod = require(/* webpackIgnore: true */ 'runtime-module')
```

### `turbopackOptional` (Turbopack only)

Use this comment to suppress build errors when a module might not exist. The import will still throw at runtime if the module is missing:

```js
// No build error if './optional-feature' doesn't exist
// Runtime will throw MODULE_NOT_FOUND if executed
const feature = await import(/* turbopackOptional: true */ './optional-feature')

// Also works with require
const mod = require(/* turbopackOptional: true */ './optional-module')
```

This is useful for:

- Conditional features that may not be installed
- Plugin systems where modules are optional
- Gradual migrations where some files may not exist yet

> **Good to know:**
>
> `webpackOptional` is not supported. Use `turbopackOptional` instead when using Turbopack.

---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/docs/llms.txt](/docs/llms.txt)