Lazy Loading Client Components and Libraries in Next.js – Optimize Performance with Dynamic Imports and Suspense

Lazy loading in Next.js improves performance by deferring the loading of Client Components and external libraries until they’re needed. This article explains how to use next/dynamic and React.lazy, manage SSR behavior, load third-party libraries on demand, and customize loading states.

Lazy LoadingClient Componentnext/dynamicSuspense

~2 دقیقه مطالعه · آخرین به‌روزرسانی ۶ آبان ۱۴۰۴

Introduction


Lazy loading in Next.js allows you to defer the loading of Client Components and libraries until they’re actually needed. This reduces the initial JavaScript bundle size and improves page load performance.


Two Approaches


  • Using next/dynamic: Combines React.lazy and Suspense with SSR support
  • Using React.lazy and Suspense: Works for Client Components only

Example: Lazy Loading Client Components


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

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>
      <ComponentA />
      {showMore && <ComponentB />}
      <button onClick={() => setShowMore(!showMore)}>Toggle</button>
      <ComponentC />
    </div>
  )
}

Disabling SSR for Client Components


To prevent server-side rendering of a Client Component:

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

Lazy Loading Server Components


When dynamically importing a Server Component, only its Client children are lazy-loaded. The ssr: false option is not supported for Server Components.

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

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

Loading External Libraries on Demand


Use import() to load third-party libraries only when needed:

'use client'
import { useState } from 'react'

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

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

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

Custom Loading Component


'use client'
import dynamic from 'next/dynamic'

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

export default function Page() {
  return <WithCustomLoading />
}

Importing Named Exports


To dynamically import a named export:

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

Conclusion


Lazy loading in Next.js is a powerful technique for optimizing performance. By deferring the loading of Client Components and libraries, managing SSR behavior, and customizing loading states, you can build faster and more responsive applications.


نوشته و پژوهش‌شده توسط دکتر شاهین صیامی

مقالات مرتبط

Advanced Client-Side Routing and Performance Hooks in Next.js

Next.js provides a rich set of client-side hooks and caching utilities that empower developers to build dynamic, responsive, and secure applications. From reading route parameters to tracking navigation state and reporting performance metrics, this guide walks you through the most important tools available in the App Router.

ادامه

Handling Authorization and Caching in Next.js: A Developer’s Guide

Next.js introduces powerful experimental features for access control and smart caching. This guide covers the unauthorized() function for custom 401 handling, unstable_cache for persistent memoization, updateTag for instant cache invalidation, and useLinkStatus for inline navigation feedback. Learn how to use these tools to build secure, performant, and responsive applications.

ادامه

redirect and refresh in Next.js — Smart Redirects and Client Refreshing via Server Actions

The redirect function in Next.js allows you to navigate users to a new route, returning either a 307 or 303 HTTP response depending on context. It works in Server Components, Client Components, Route Handlers, and Server Actions. The refresh function is used exclusively within Server Actions to refresh the client router. This article explains how both functions work, with practical examples and key considerations.

ادامه

NextRequest and NextResponse in Next.js — Managing Cookies, Headers, Redirects, and Rewrites

Next.js extends the native Web Request and Response APIs with NextRequest and NextResponse, offering powerful tools for managing cookies, headers, redirects, rewrites, and JSON responses. These utilities simplify server-side logic and improve control over routing, personalization, and security. This guide walks through their capabilities with practical examples and best practices.

ادامه

headers, ImageResponse, notFound, and permanentRedirect in Next.js — Request Handling, Dynamic Images, Errors, and Redirects

Next.js offers powerful tools for handling HTTP requests and responses in Server Components. The headers function lets you read incoming request headers. ImageResponse allows you to generate dynamic images using JSX and CSS. The notFound function renders a custom 404 page, and permanentRedirect enables permanent redirection to another route. This article explains how to use each feature with practical examples.

ادامه

A Complete Guide to Using metadata and generateMetadata in Next.js

In modern versions of Next.js, managing page metadata is more powerful and intuitive than ever. Metadata is automatically injected into the <head> of your pages and plays a vital role in SEO, social sharing, and user experience. This guide explains the two main ways to define metadata: using the static metadata object and the dynamic generateMetadata function.

ادامه