惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

S
Secure Thoughts
Recent Commits to openclaw:main
Recent Commits to openclaw:main
H
Heimdal Security Blog
SecWiki News
SecWiki News
H
Hacker News: Front Page
N
News | PayPal Newsroom
L
LINUX DO - 最新话题
N
News and Events Feed by Topic
TaoSecurity Blog
TaoSecurity Blog
AI
AI
C
Cybersecurity and Infrastructure Security Agency CISA
Scott Helme
Scott Helme
PCI Perspectives
PCI Perspectives
S
Securelist
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Cyberwarzone
Cyberwarzone
A
Arctic Wolf
Forbes - Security
Forbes - Security
T
Tor Project blog
Spread Privacy
Spread Privacy
WordPress大学
WordPress大学
I
Intezer
Martin Fowler
Martin Fowler
Help Net Security
Help Net Security
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Cisco Talos Blog
Cisco Talos Blog
Latest news
Latest news
博客园 - 司徒正美
W
WeLiveSecurity
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
V
V2EX
P
Palo Alto Networks Blog
Google DeepMind News
Google DeepMind News
IT之家
IT之家
阮一峰的网络日志
阮一峰的网络日志
V
Vulnerabilities – Threatpost
Jina AI
Jina AI
S
Security Affairs
Hacker News - Newest:
Hacker News - Newest: "LLM"
Simon Willison's Weblog
Simon Willison's Weblog
Project Zero
Project Zero
T
Threatpost
P
Privacy International News Feed
人人都是产品经理
人人都是产品经理
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Application and Cybersecurity Blog
Application and Cybersecurity Blog
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Next.js Dynamic Imports & Lazy Loading: The Complete Guide (2026)
Carlos Oliva Pascual · 2026-06-26 · via DEV Community

Carlos Oliva Pascual

Every Next.js app has the same performance trap: you ship a heavy component that every user has to download, even when most users never interact with it. A rich text editor on an admin page. A chart library on a dashboard that half the users never open. A date picker that appears behind a modal.

Dynamic imports are the fix. They split these components into separate chunks that only load when needed. Less JavaScript on initial load, faster first paint, better Core Web Vitals.

This guide covers every dynamic import pattern in Next.js 15, when to use each, and how to measure the impact.

The Problem: Bundle Size

A Next.js page has two phases: the initial HTML from the server and the JavaScript bundle the browser has to parse and execute. The larger that bundle, the longer the Time to Interactive.

A single heavy library can add hundreds of kilobytes. Common offenders:

  • Chart libraries (Recharts, Chart.js, Victory) — 200–400KB each
  • Rich text editors (TipTap, Slate, Quill) — 300–600KB
  • Date pickers with locale data — 100–200KB
  • Map libraries (Leaflet, MapboxGL) — 300KB+
  • PDF renderers — 500KB+

If these are statically imported at the top of a file, every visitor downloads them on first load — including visitors who never see that component.

next/dynamic: The Next.js Approach

next/dynamic is Next.js's built-in wrapper around React.lazy with extra features for SSR control.

import dynamic from 'next/dynamic'

// Static import — included in main bundle
// import { HeavyChart } from '@/components/heavy-chart'

// Dynamic import — loaded only when rendered
const HeavyChart = dynamic(() => import('@/components/heavy-chart'), {
  loading: () => <div className="h-64 animate-pulse bg-muted rounded-lg" />,
})

export default function DashboardPage() {
  return (
    <main>
      <h1>Dashboard</h1>
      <HeavyChart data={data} />
    </main>
  )
}

When Next.js builds this page, HeavyChart is split into a separate JavaScript chunk. The browser only fetches that chunk when DashboardPage renders and HeavyChart is actually in the tree.

The loading prop

The loading prop renders while the chunk is fetching. Design it to match the real component's dimensions to avoid layout shift:

const RevenueChart = dynamic(() => import('@/components/revenue-chart'), {
  loading: () => (
    <div className="flex h-64 items-center justify-center rounded-lg border bg-muted/30">
      <div className="flex flex-col items-center gap-2 text-muted-foreground">
        <div className="h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent" />
        <span className="text-sm">Loading chart...</span>
      </div>
    </div>
  ),
})

ssr: false — Client-Only Components

Some components can't render on the server at all: they use window, document, browser APIs, or libraries that aren't SSR-compatible.

Without ssr: false, these cause hydration errors or server-side exceptions. With it, Next.js skips server rendering entirely and renders only on the client:

// ❌ Breaks on the server — window is not defined
import { Map } from '@/components/map'

// ✅ Server renders nothing, client loads and renders normally
const Map = dynamic(() => import('@/components/map'), {
  ssr: false,
  loading: () => <div className="h-64 bg-muted rounded-lg" />,
})

Common use cases for ssr: false:

// Rich text editor
const RichTextEditor = dynamic(() => import('@/components/rich-text-editor'), {
  ssr: false,
  loading: () => <div className="h-48 animate-pulse bg-muted rounded-lg" />,
})

// Interactive map
const InteractiveMap = dynamic(() => import('@/components/map'), {
  ssr: false,
  loading: () => <div className="h-96 bg-muted rounded-lg" />,
})

// QR code generator (uses Canvas API)
const QRGenerator = dynamic(() => import('@/components/qr-generator'), {
  ssr: false,
})

Note: When you use ssr: false, the component is excluded from the server-rendered HTML entirely. The loading placeholder is what users with slow connections or JS disabled will see. Make sure it communicates something meaningful, not just a blank space.

Dynamic Imports with Named Exports

import() returns the default export. For named exports, map them in the promise:

// Named export: export function BarChart() { ... }
const BarChart = dynamic(
  () => import('@/components/charts').then((mod) => mod.BarChart),
  { loading: () => <ChartSkeleton /> }
)

// Or use a re-export file
// lib/dynamic-charts.ts
export const DynamicBarChart = dynamic(
  () => import('@/components/charts').then((mod) => mod.BarChart),
  { ssr: false }
)

next/dynamic vs React.lazy

Both lazy-load components, but they're different tools:

next/dynamic React.lazy
SSR control ssr: false option No SSR support
Loading state loading prop Requires <Suspense>
Works in Server Components No (use in Client Components) No
Named exports .then((mod) => mod.Export) Same pattern
Next.js integration Yes — chunk naming, preloading Partial

In the Next.js App Router, both work in Client Components. next/dynamic is more ergonomic for Next.js-specific patterns (especially ssr: false). React.lazy is fine for pure React component lazy loading where you don't need SSR control.

// React.lazy — fine for App Router Client Components
'use client'

import { lazy, Suspense } from 'react'

const HeavyComponent = lazy(() => import('@/components/heavy-component'))

export function Section() {
  return (
    <Suspense fallback={<div className="h-32 animate-pulse bg-muted rounded" />}>
      <HeavyComponent />
    </Suspense>
  )
}

Conditional Loading: Load Only When Needed

The biggest win is loading components only when the user actually needs them:

'use client'

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

const PDFViewer = dynamic(() => import('@/components/pdf-viewer'), {
  ssr: false,
  loading: () => <div className="h-96 animate-pulse bg-muted rounded" />,
})

export function DocumentCard({ url }: { url: string }) {
  const [showPreview, setShowPreview] = useState(false)

  return (
    <div>
      <button onClick={() => setShowPreview(true)}>
        Preview document
      </button>

      {/* PDFViewer chunk only downloads when the user clicks */}
      {showPreview && <PDFViewer url={url} />}
    </div>
  )
}

The PDF viewer library — often 500KB+ — doesn't download until the user explicitly requests a preview.

Dynamic Imports for Heavy Libraries

When the heavy thing is a library rather than a component, use the dynamic import() function directly:

'use client'

import { useState } from 'react'

export function ExportButton({ data }: { data: unknown[] }) {
  const [isExporting, setIsExporting] = useState(false)

  async function handleExport() {
    setIsExporting(true)

    // xlsx only loads when the user clicks Export
    const { utils, writeFile } = await import('xlsx')

    const ws = utils.json_to_sheet(data)
    const wb = utils.book_new()
    utils.book_append_sheet(wb, ws, 'Data')
    writeFile(wb, 'export.xlsx')

    setIsExporting(false)
  }

  return (
    <button onClick={handleExport} disabled={isExporting}>
      {isExporting ? 'Exporting...' : 'Export to Excel'}
    </button>
  )
}

Preloading: Anticipate Before the User Clicks

If you know the user is likely to trigger a dynamic import (hovering over a button, scrolling near a component), preload the chunk early:

import dynamic from 'next/dynamic'

const EditModal = dynamic(() => import('@/components/edit-modal'))

// Preload the chunk when the user hovers
function EditButton() {
  return (
    <button
      onMouseEnter={() => {
        // Starts fetching the chunk — by the time they click, it's ready
        import('@/components/edit-modal')
      }}
      onClick={() => setModalOpen(true)}
    >
      Edit
    </button>
  )
}

This pattern eliminates the loading flash for fast users: the chunk starts downloading on hover and is usually ready by the time they click.

What to Dynamically Import (and What Not To)

Good candidates for dynamic imports:

  • Heavy third-party libraries used conditionally (chart libraries, editors, PDF viewers)
  • Components behind user interaction (modals, drawers, expanded sections)
  • Components at the bottom of long pages (below the fold)
  • Admin/settings pages that regular users rarely visit
  • Anything with window or document access

Bad candidates for dynamic imports:

  • Core UI components used everywhere (buttons, inputs, layout)
  • Components needed for initial render (hero sections, navigation)
  • Small utilities where the dynamic import overhead outweighs the savings
  • Components used immediately on every page load

The test: if the user can complete their primary action on the page without ever rendering the component, it's a candidate for lazy loading.

Measuring the Impact

Bundle analyzer — see what's in your bundles before and after:

npm install --save-dev @next/bundle-analyzer

// next.config.ts
import withBundleAnalyzer from '@next/bundle-analyzer'

const config = withBundleAnalyzer({
  enabled: process.env.ANALYZE === 'true',
})

export default config

ANALYZE=true npm run build

Open the visualization and look for large modules in your initial bundle that could be deferred.

Quick Reference

// Basic dynamic import with loading state
const Component = dynamic(() => import('./component'), {
  loading: () => <Skeleton />,
})

// Client-only component
const BrowserComponent = dynamic(() => import('./browser-component'), {
  ssr: false,
  loading: () => <Placeholder />,
})

// Named export
const NamedExport = dynamic(
  () => import('./module').then((m) => m.NamedExport)
)

// Conditional render (most impactful pattern)
{isOpen && <DynamicModal />}

// Preload on hover
onMouseEnter={() => import('./component')}

// Dynamic library import in a function
const { default: heavyLib } = await import('heavy-lib')

The principle is the same throughout: defer downloading JavaScript until it's actually needed. The browser does less work on initial load, the user gets an interactive page sooner, and the code that most users never see doesn't cost them anything.


Full article at stacknotice.com/blog/nextjs-dynamic-imports-lazy-loading-2026