Hello! Welcome to the next lesson in our journey to master React.
In our last lesson, we tackled how to build resilient applications using Error Boundaries. We saw how these special class components can catch runtime errors in the component tree and display a graceful fallback UI, preventing a full application crash.
Today, we'll continue our exploration of building production-ready applications by focusing on performance. Specifically, we will learn how to apply code splitting with React.lazy and <Suspense> to improve the initial load time of our application. This technique is fundamental to ensuring your users have a fast and responsive experience from the very first visit.
1. The Problem: The Monolithic Bundle
When we build a React application with a bundler like Vite, all of our application's code—components, libraries, and utilities—is typically bundled into a few JavaScript files. As an application grows, so does the size of this bundle. A user's browser must download, parse, and execute this entire bundle before they can interact with the app. This can lead to long initial load times, especially on slower networks.
The solution to this is code splitting. Instead of downloading everything at once, we can split the bundle into smaller "chunks" and load them on demand, as the user needs them.

2. How Code Splitting Works: Dynamic Imports
The foundation of code splitting in modern JavaScript is the dynamic import() syntax. Unlike the static import statements you typically place at the top of a file, a dynamic import() is called like a function and returns a Promise.
When a bundler like Vite encounters a dynamic import(), it automatically creates a separate chunk for that module.
Speed Up Your React Apps With Code Splitting
To understand the core concept, let's watch a section of the video 'Speed Up Your React Apps With Code Splitting' from Web Dev Simplified. This part explains why code splitting is beneficial and demonstrates how a dynamic import works with a simple function, separating it from the main bundle.
Watch from 01:08 to 04:27. Pay attention to how the application's initial source files are inspected 'before' code splitting, and how a dynamic import() for a sum function prevents that code from being loaded until a button is clicked.
As you saw, the code for the sum function wasn't downloaded until it was actually needed. This is powerful, but how do we apply this concept to React components, which aren't called in the same way as a regular function?
3. Code Splitting React Components with React.lazy and <Suspense>
React provides a simple and elegant API to integrate dynamic imports into your component tree: React.lazy and the <Suspense> component.
React.lazy(): A function that lets you render a dynamically imported component as a regular component. It takes a function as an argument that must call a dynamicimport(). Thisimport()must resolve to a module with adefaultexport containing a React component.<Suspense>: A component that lets you specify a loading indicator (a "fallback" UI) if the components in the tree below it are not yet ready to render.
When React tries to render a lazy-loaded component for the first time, it triggers the dynamic import. While the code is being fetched over the network, the component "suspends" rendering. React travels up the tree to find the nearest <Suspense> boundary and renders its fallback prop until the component is ready.
This sequence diagram illustrates the process:
Let's see the code in action.
Lazy Loading, Async Rendering & Data Fetching (React 18/19)
The article 'Lazy Loading, Async Rendering & Data Fetching' provides a clear, concise example of how these two pieces fit together. It's a great reference for the basic syntax.
Read the section titled 'Lazy Loading (Code Splitting)'. Focus on the code example showing how to wrap a lazy-loaded HeavyComponent inside a Suspense boundary.
4. Route-Based Code Splitting
The most common and effective use case for code splitting is at the route level. There's no reason for a user on the /home page to download all the code for the /dashboard or /settings pages. By lazy-loading your page components, you ensure users only download the code for the page they are currently viewing.
Since you're already familiar with React Router from Module 9, let's see how to integrate React.lazy with it.
import React, { Suspense } from 'react';
import { BrowserRouter, Routes, Route, Link } from 'react-router-dom';
import { ErrorBoundary } from './ErrorBoundary'; // Assuming you have this from the last lesson
// Static import for a component needed everywhere
import { Nav } from './components/Nav';
// Dynamic imports for page-level components
const HomePage = React.lazy(() => import('./pages/HomePage'));
const AboutPage = React.lazy(() => import('./pages/AboutPage'));
function App() {
return (
<BrowserRouter>
<Nav />
{/*
Wrap Suspense around the Routes. If a lazy component fails to load
(e.g., network error), the ErrorBoundary will catch it.
*/}
<ErrorBoundary fallback={<div>Failed to load page. Please refresh.</div>}>
<Suspense fallback={<h1>Loading page...</h1>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/about" element={<AboutPage />} />
</Routes>
</Suspense>
</ErrorBoundary>
</BrowserRouter>
);
}
Notice a few key things in this example:
- We define
HomePageandAboutPageusingReact.lazy. - The
<Routes>component is wrapped in<Suspense>. When the user navigates to/about, React will suspend and show the "Loading page..." fallback while it fetches the code forAboutPage. - Connecting to our last lesson: The
<Suspense>component itself is wrapped in anErrorBoundary. If the dynamicimport()fails (e.g., due to a network error), the promise will reject, and this error will be caught by our Error Boundary, preventing a crash.
Test your understanding!
You are building a large e-commerce application. The ProductDetailsPage component is very large because it includes a complex 3D model viewer library. The CheckoutPage is also large due to payment processing SDKs. The HomePage is relatively small.
How would you structure your router using React.lazy to ensure the best initial load performance when a user first lands on the HomePage?
Show answer
You would lazy-load both the ProductDetailsPage and the CheckoutPage, but statically import the HomePage if it's the main landing page and you want it to appear as fast as possible without a loading fallback. However, for consistency and to prepare for growth, lazy-loading all pages is a common and robust pattern.
A good implementation would look like this:
import React, { Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import HomePage from './pages/HomePage'; // Can be static if it's the main entry
const ProductDetailsPage = React.lazy(() => import('./pages/ProductDetailsPage'));
const CheckoutPage = React.lazy(() => import('./pages/CheckoutPage'));
function AppRoutes() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
<Route path="/" element={<HomePage />} />
<Route path="/products/:id" element={<ProductDetailsPage />} />
<Route path="/checkout" element={<CheckoutPage />} />
</Routes>
</Suspense>
);
}
This ensures the heavy code for the product and checkout pages is not part of the initial bundle, making the HomePage load much faster.
5. Handling Common Scenarios and Pitfalls
While the basic usage is straightforward, there are a couple of common issues you might encounter.
A. Components with Named Exports
React.lazy currently only supports default exports. If you try to lazy-load a component that is a named export, it will fail.
// In ./components/AdminPanel.tsx
export const AdminPanel = () => <div>Admin Controls</div>; // Named export
// In App.tsx
const AdminPanel = React.lazy(() => import('./components/AdminPanel')); // This will break!
The fix is to adjust the promise returned by the dynamic import to create a "fake" default export.
Speed Up Your React Apps With Code Splitting
The same Web Dev Simplified video provides an excellent, clear explanation and solution for this exact problem. He shows how to use .then() on the dynamic import promise to remap the named export to a default property.
Watch the segment from 08:48 to 10:42. The key is understanding how the module object is destructured and re-exported within the promise chain.
Here's the pattern from the video applied to our AdminPanel example:
const AdminPanel = React.lazy(() =>
import('./components/AdminPanel').then(module => ({
default: module.AdminPanel,
}))
);
B. Conditional Rendering
Code splitting isn't just for routes. You can apply it to any component that is rendered conditionally. This is perfect for features that not all users will see or use, such as:
- A complex modal dialog.
- An admin dashboard panel.
- A heavy charting library that's only shown when a user clicks "View Report".
Speed Up Your React Apps With Code Splitting
Let's return to the Web Dev Simplified video one last time to see a practical example of lazy-loading a conditionally rendered component.
Watch from 10:42 to 12:51. This section demonstrates how to lazy-load an AdminData component that is only shown if a user is an admin, preventing non-admin users from ever downloading that code.
6. Code Splitting with Vite
The great news is that because our project is set up with Vite, code splitting works out of the box. Vite's build process automatically detects dynamic import() calls and creates the necessary chunks. There is no extra configuration required to get started.
Optimizing React Apps with Code Splitting and Lazy Loading
This article from Medium, 'Optimizing React Apps with Code Splitting and Lazy Loading,' has a specific section on Vite that confirms this behavior.
Read the sections 'Adding Code Splitting and Lazy Loading with Vite' and 'How Vite Handles Code Splitting'. This will reinforce that the tools you're already using are built for modern performance patterns like this one.
Conclusion
You've now learned a powerful technique for dramatically improving the performance of your React applications. By deferring the loading of non-critical code, you provide a faster, snappier initial experience for your users.
Key Takeaways:
- Code Splitting breaks a large application bundle into smaller chunks that are loaded on demand, improving initial load time.
- The
React.lazy()function allows you to define a component that will be loaded dynamically using theimport()syntax. - The
<Suspense>component provides a declarativefallbackUI to show while lazy components are being fetched. - The most common patterns are route-based code splitting (lazy-loading pages) and conditional code splitting (lazy-loading modals, panels, etc.).
- You must handle components with named exports by transforming the resolved promise.
- Always wrap your
<Suspense>boundary with an Error Boundary to gracefully handle network errors or other failures during the dynamic import.
Preview of the Next Lesson:
We've seen that Vite handles code splitting automatically. In our next lesson, we'll dive deeper into configuring a build process with Vite for a production-optimized application. We'll explore how you can further customize the build output, manage assets, and ensure your application is as small and fast as possible when you deploy it.