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

推荐订阅源

C
Cybersecurity and Infrastructure Security Agency CISA
N
News and Events Feed by Topic
S
Securelist
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Spread Privacy
Spread Privacy
T
Threat Research - Cisco Blogs
T
Tor Project blog
C
Cyber Attacks, Cyber Crime and Cyber Security
K
Kaspersky official blog
L
LINUX DO - 热门话题
T
The Exploit Database - CXSecurity.com
S
Schneier on Security
A
Arctic Wolf
Security Latest
Security Latest
T
Threatpost
P
Palo Alto Networks Blog
Simon Willison's Weblog
Simon Willison's Weblog
AWS News Blog
AWS News Blog
Cyberwarzone
Cyberwarzone
L
Lohrmann on Cybersecurity
P
Privacy International News Feed
V
Vulnerabilities – Threatpost
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cisco Talos Blog
Cisco Talos Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
G
GRAHAM CLULEY
The Hacker News
The Hacker News
C
CERT Recently Published Vulnerability Notes
Know Your Adversary
Know Your Adversary
I
Intezer
Scott Helme
Scott Helme
T
Tenable Blog
NISL@THU
NISL@THU
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Cisco Blogs
N
News and Events Feed by Topic
P
Proofpoint News Feed
P
Privacy & Cybersecurity Law Blog
Project Zero
Project Zero
Latest news
Latest news
Hacker News: Ask HN
Hacker News: Ask HN
Recent Commits to openclaw:main
Recent Commits to openclaw:main
Forbes - Security
Forbes - Security
Security Archives - TechRepublic
Security Archives - TechRepublic
AI
AI
S
Security Affairs
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
D
Docker
P
Proofpoint News Feed
博客园 - Franky

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
React.lazy() Route Code Splitting Explained
Ashish Kumar · 2026-05-11 · via DEV Community

Related: JavaScript Bundle Analysis: Tree Shaking and Code Splitting Explained covers how bundlers construct module graphs and where tree shaking fails, which is the foundation for understanding what code splitting actually does.

The size of your JavaScript bundle is not the number that matters for first load. What matters is how much of that bundle is needed to render the page the user actually landed on. A 5MB React application where the user landed on the marketing homepage might need 80KB to show that page. The other 4.92MB is code for routes the user has not visited and may never visit. React.lazy() is how you stop shipping those 4.92MB on first load.

What this covers: What React.lazy() does to the bundle at build time, how Suspense fits into the loading flow, how to confirm the split actually happened, the cases where it silently fails, and the preloading pattern that prevents waterfall fetches on navigation.

Diagram showing a single large bundle being split into a small initial chunk and separate route chunks that load on demand when the user navigates.


What React.lazy() does to the bundle

React.lazy() takes a function that returns a dynamic import(). The key word is dynamic. A static import at the top of a file is analyzed at build time and the imported module is included in the same output chunk. A dynamic import is a split point: the bundler creates a separate output chunk containing the dynamically imported module and all of its unique dependencies.

// Static import: Dashboard ends up in the same chunk as App

// Dynamic import with React.lazy(): Dashboard becomes a separate chunk
const Dashboard = lazy(() => import('./pages/Dashboard'));

Enter fullscreen mode Exit fullscreen mode

When you switch from a static import to React.lazy(), your bundler (Vite, Webpack, or otherwise) creates a new file in the build output. Instead of one bundle, you get the main bundle plus a chunk file specifically for Dashboard and everything it imports that is not already in the main bundle.

The main bundle shrinks by the size of Dashboard and its unique dependencies. The Dashboard chunk is downloaded on demand when the user navigates to the dashboard route.


const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
const AdminPanel = lazy(() => import('./pages/AdminPanel'));

function App() {
  return (
    }>

    </Suspense>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this setup, a user who lands on / downloads the main bundle plus the Home chunk. They do not download anything for Dashboard, Settings, or AdminPanel until they navigate to those routes.


How Suspense fits in

React.lazy() by itself will throw an error if you try to render the component before its chunk has loaded. Suspense catches that error and shows a fallback UI while the chunk downloads.

The mechanics: when React tries to render a lazy component and the chunk is not yet loaded, the component throws a Promise. Suspense catches the thrown Promise and renders the fallback. When the Promise resolves (the chunk has downloaded), Suspense re-renders the tree with the actual component.

This is the same Suspense boundary you would use for data fetching. The behavior is identical: throw a Promise to signal "not ready," catch it at the nearest Suspense boundary, show fallback while waiting, render real content when ready.

// Suspense can wrap individual routes or the entire app
// Wrapping the whole app is simpler; wrapping per-route allows per-route fallbacks

// Per-route fallbacks (more control):
function App() {
  return (

        }
      />
      }>

          </Suspense>
        }
      />
    </Routes>
  );
}

Enter fullscreen mode Exit fullscreen mode

For most applications, a single Suspense boundary around all routes is simpler and sufficient. The fallback can be a generic page loader or even null if you prefer a blank transition. The key constraint is that the Suspense boundary must be an ancestor of the lazy component in the React tree.


Verifying the split actually happened

The most common mistake with code splitting is thinking you have done it when you have not. Before assuming a React.lazy() conversion worked, verify it.

Method 1: Check the build output. Run npm run build and look at the output files. A successful route split produces separate chunk files:

dist/assets/index-a1b2c3.js       (main bundle, ~80KB)
dist/assets/Dashboard-d4e5f6.js   (dashboard chunk, ~45KB)
dist/assets/Settings-g7h8i9.js    (settings chunk, ~22KB)
dist/assets/AdminPanel-j0k1l2.js  (admin chunk, ~38KB)

Enter fullscreen mode Exit fullscreen mode

If you see only one JavaScript file or if all your route components appear in index.js, the split did not happen.

Method 2: Use bundle analysis. With Vite, add the visualizer plugin:

// vite.config.ts

  plugins: [
    visualizer({ filename: 'bundle-stats.html', gzipSize: true })
  ]
};

Enter fullscreen mode Exit fullscreen mode

After building, open bundle-stats.html. If the split worked, you will see your route components in separate rectangles outside the main bundle rectangle. If they are inside the main bundle, something went wrong.

Method 3: Check the Network tab. Open Chrome DevTools, go to the Network tab, filter by JS, and navigate between routes. When you navigate to a route for the first time, you should see a new JS file appear in the network requests. If no new files appear, the code was included in the initial bundle.


Why the split silently fails

Static imports elsewhere in the file. If you import a component from a file that is also imported statically somewhere in the main bundle, the component will be included in the main bundle regardless of your lazy() call. The bundler deduplicates modules, so a module that is reachable through a static import path will not be split out.

// This file statically imports Dashboard, so Dashboard is in the main bundle

// This lazy() call does nothing useful because Dashboard is already included
const DashboardLazy = lazy(() => import('./pages/Dashboard'));

Enter fullscreen mode Exit fullscreen mode

Check that the component you are splitting is not imported anywhere else in the main bundle's dependency chain.

Eager imports in the entry point. The entry point (usually main.tsx or App.tsx) must not have static imports for the components you want to split.

// main.tsx: these static imports pull everything into the initial bundle

// All of these are now in the initial bundle regardless of lazy() usage below

Enter fullscreen mode Exit fullscreen mode

If your entry file imports these components, remove those imports and rely entirely on React.lazy() for the route components.

Shared dependencies. If Dashboard and Settings both import a large shared library, that library goes into the main chunk (or a separate vendor chunk) rather than being duplicated in each route chunk. This is correct behavior and not a failure. The route chunks will be smaller than you expect because shared code is extracted automatically.


Named chunks for production debugging

By default, bundlers generate hash-based chunk names like chunk-d4e5f6.js. These are stable for caching but unreadable in production error logs.

Add a magic comment to name chunks:

const Dashboard = lazy(() =>
  import(
    /* webpackChunkName: "dashboard" */
    './pages/Dashboard'
  )
);

// In Vite, use vitePreload (Vite handles naming automatically based on file names in most cases)
// But you can also add rollupOptions in vite.config.ts to control chunk naming

Enter fullscreen mode Exit fullscreen mode

With named chunks, your build output becomes:

dist/assets/dashboard-d4e5f6.js
dist/assets/settings-g7h8i9.js
dist/assets/admin-panel-j0k1l2.js

Enter fullscreen mode Exit fullscreen mode

Production stack traces and network logs become readable.


Preloading chunks on hover to eliminate waterfall

The biggest UX issue with lazy loading is the delay when a user first navigates to a route. The sequence is: user clicks link, React renders null (Suspense fallback), browser fetches chunk, chunk executes, component renders. That network fetch adds latency.

The standard fix is to preload the chunk before the user clicks, triggered on hover or focus:

// Preload helper
function preloadComponent(factory) {
  const Component = lazy(factory);
  // Trigger the import() immediately (while hovering)
  // React.lazy caches the result, so when Suspense renders it, the chunk is ready
  Component.preload = factory;
  return Component;
}

const Dashboard = lazy(() => import('./pages/Dashboard'));

// In your nav link:
function NavLink({ to, children }) {
  const navigate = useNavigate();

  const handleMouseEnter = () => {
    // Trigger the chunk fetch when user hovers the link
    import('./pages/Dashboard');
  };

  return (
    <a
      href={to}
      onMouseEnter={handleMouseEnter}
      onFocus={handleMouseEnter}
    >
      {children}
    </a>
  );
}

Enter fullscreen mode Exit fullscreen mode

When the user hovers a navigation link, the chunk download starts. By the time they click and React tries to render the route, the chunk is already in the browser's cache. The Suspense fallback either never shows or shows for under 100ms.

React Router v6 handles this through the loader pattern in the data router API. Next.js has built-in prefetching for <Link> components. For custom setups, the hover-triggered import approach above covers most cases.


The numbers in practice

Here is a realistic example from a mid-size React application before and after route splitting:

Route Before (included in initial bundle) After (separate chunk, loaded on demand)
Homepage 1.2MB total initial JS 85KB initial bundle
Dashboard (already loaded) 245KB, loads when user navigates
Settings (already loaded) 78KB, loads when user navigates
Admin Panel (already loaded) 312KB, loads when user navigates
Reports (already loaded) 168KB, loads when user navigates

A user who only uses the homepage never downloads the Dashboard chunk. A user who does use the dashboard downloads 245KB for it specifically, rather than getting it bundled with everything else. The browser can also cache each chunk separately, so after a first visit to the dashboard, subsequent visits serve it from cache regardless of whether the main bundle changed.

The improvement in Time to Interactive for first-time visitors is proportional to how much of the pre-split bundle was route-specific code. In applications with many routes and large per-route dependencies, the improvement can be dramatic. In small applications with 3 routes and shared components, the split saves less. Measure your bundle before and after to know if the split is worth the added complexity.


Read the original article on Renderlog.in:
https://renderlog.in/blog/react-lazy-route-code-splitting-guide/

If you found this helpful, I've also built some free tools for developers and everyday users. Feel free to try them once:

JSON Tools: https://json.renderlog.in
Text Tools: https://text.renderlog.in
QR Tools: https://qr.renderlog.in