Popular Searches
Popular Course Categories
Popular Courses

Code Splitting

Code Splitting

React Performance Optimization

Code Splitting in React – Complete Notes

1. Introduction to Code Splitting

Code Splitting is a performance optimization technique in React that divides an application's JavaScript code into smaller bundles or chunks. Instead of loading the entire application code at once, the browser can load only the code required for the current page or feature and load additional code when needed.

As a React application grows, it may contain many components, libraries, pages, and features. Loading all this JavaScript during the initial page load can increase download time and delay the application's interactivity. Code Splitting helps reduce the amount of JavaScript required initially and can improve the user experience.

React supports component-level lazy loading through React.lazy() and Suspense. Dynamic imports are commonly used with bundlers to create separate chunks.

2. Why Is Code Splitting Important?

Without Code Splitting, an application may include code for every page and feature in its initial JavaScript bundle. Users may have to download code for sections they never visit.

For example, an e-commerce application may contain a homepage, product catalog, shopping cart, checkout page, account dashboard, and reports section. A visitor opening the homepage does not necessarily need the code for every other section immediately.

Code Splitting allows these features to be loaded separately when appropriate.

  • Reduces the amount of JavaScript needed for the initial page.
  • Can improve initial loading performance.
  • Allows less frequently used features to load on demand.
  • Can improve navigation and perceived responsiveness.
  • Helps organize large applications into manageable modules.
  • Can reduce unnecessary downloading of code that users never access.

3. What Is a JavaScript Bundle?

A JavaScript bundle is a file produced by a bundler from application code and its dependencies. Bundlers such as Vite, webpack, and Rollup analyze imports and package code for deployment.

In a small application, the initial bundle may be relatively small. In a large application, it may include many components and third-party libraries, making it larger and slower to download and process.

Code Splitting allows a bundler to generate multiple chunks instead of placing all code into one large initial bundle.

Example:

src/
├── App.jsx
├── Home.jsx
├── Dashboard.jsx
├── Reports.jsx
└── Settings.jsx

A bundler may place frequently needed code in the initial bundle and create separate chunks for Dashboard, Reports, or Settings when the application's import structure supports splitting.

4. How Code Splitting Works

  1. The developer separates application functionality into components or modules.
  2. Dynamic imports identify code that can be loaded asynchronously.
  3. The bundler creates separate chunks where appropriate.
  4. The browser loads the initial application code.
  5. When a lazy-loaded component is needed, the browser requests its chunk.
  6. React can display a loading fallback while the component code is being loaded.
  7. After the chunk loads successfully, React renders the component.

Code Splitting does not necessarily reduce the total amount of JavaScript in an application. Instead, it can reduce how much code must be downloaded and processed at the beginning.

5. Code Splitting with Dynamic Imports

Dynamic imports use the import() syntax to load a module asynchronously. Unlike a static import, a dynamic import returns a Promise that resolves to the module after it has been loaded.

Static import example:

import { calculateTotal } from "./utils.js";
console.log(calculateTotal(100, 200));

With a static import, the module is part of the application's statically analyzed dependency graph. Depending on the bundler, it may be included in the initial bundle or another statically generated chunk.

Dynamic import example:

import("./utils.js")
  .then((module) => {
    console.log(module.calculateTotal(100, 200));
  })
  .catch((error) => {
    console.error("Module loading failed:", error);
  });

Explanation: The dynamic import returns a Promise. When the module loads, the Promise resolves to a module object containing its exports. Modern bundlers commonly use this syntax as a code-splitting point.

6. Code Splitting with React.lazy()

React.lazy() lets React load a component's code only when that component is first rendered. It is commonly used with a dynamic import.

Syntax:

import { lazy } from "react";
const Dashboard = lazy(() => import("./Dashboard.jsx"));

The import function returns a Promise that resolves to a module with a default export containing a valid React component.

Example component:

// Dashboard.jsx
export default function Dashboard() {
  return (
    <div>
      <h2>Dashboard</h2>
      <p>Welcome to your dashboard.</p>
    </div>
  );
}

In this example, Dashboard can be loaded on demand rather than being eagerly imported into the component that declares it.

7. Using Suspense with React.lazy()

When a lazy-loaded component is still loading, React needs a fallback interface to display. The Suspense component provides this loading state through its fallback prop.

Example:

import { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./Dashboard.jsx"));
function App() {
  return (
    <div>
      <h1>My React Application</h1>
      <Suspense fallback={<p>Loading dashboard...</p>}>
        <Dashboard />
      </Suspense>
    </div>
  );
}
export default App;

Explanation:

  • lazy() declares the component for on-demand loading.
  • Suspense defines a boundary around content that may not be ready yet.
  • fallback specifies what users see while the component is loading.
  • When the module is ready, React displays the Dashboard component.

The fallback can be a loading message, spinner, skeleton screen, or another lightweight React element.

8. Complete Code Splitting Example

Consider an application with a Home page and a Dashboard page. The Dashboard component is loaded only when the user requests it.

Dashboard.jsx

export default function Dashboard() {
  return (
    <section>
      <h2>Dashboard Page</h2>
      <p>This component is loaded on demand.</p>
    </section>
  );
}

App.jsx

import { lazy, Suspense, useState } from "react";
const Dashboard = lazy(() => import("./Dashboard.jsx"));
function App() {
  const [showDashboard, setShowDashboard] = useState(false);
  return (
    <main>
      <h1>Code Splitting Demo</h1>
      <p>The home content is available immediately.</p>
      <button onClick={() => setShowDashboard(true)}>
        Open Dashboard
      </button>
      {showDashboard && (
        <Suspense fallback={<p>Loading dashboard...</p>}>
          <Dashboard />
        </Suspense>
      )}
    </main>
  );
}
export default App;

Expected result: The application initially displays the home content and button. When the user clicks Open Dashboard, React renders the lazy component, triggering its loading if it has not been loaded yet. The fallback appears while loading, and the Dashboard appears when ready.

9. Code Splitting with React Router

Route-based Code Splitting separates the code for different application pages. It is particularly useful in applications with multiple routes because users usually need the code for only the route they are visiting.

Example:

import { lazy, Suspense } from "react";
import { BrowserRouter, Routes, Route, Link } from "react-router-dom";
const Home = lazy(() => import("./pages/Home.jsx"));
const About = lazy(() => import("./pages/About.jsx"));
const Dashboard = lazy(() => import("./pages/Dashboard.jsx"));
function App() {
  return (
    <BrowserRouter>
      <nav>
        <Link to="/">Home</Link> | 
        <Link to="/about">About</Link> | 
        <Link to="/dashboard">Dashboard</Link>
      </nav>
      <Suspense fallback={<p>Loading page...</p>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/dashboard" element={<Dashboard />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}
export default App;

Explanation: Each page is declared using React.lazy and a dynamic import. When a route needs a page that has not been loaded yet, React can show the Suspense fallback while its code loads.

Note: This example assumes React Router is installed and that the Home, About, and Dashboard files each have a default component export.

10. Component-Level vs Route-Level Code Splitting

Feature Component-Level Route-Level
Meaning Loads a specific component when needed. Loads page components when their routes are visited.
Best suited for Dialogs, editors, charts, maps, and optional features. Large applications with several pages.
Example Lazy-loading a chart component. Lazy-loading a Dashboard page.
Benefit Defers code for specific features. Defers code for pages users have not visited.

11. Code Splitting with Named Exports

React.lazy expects the loaded module to provide a default export for the component. If a module uses a named export, you can adapt it by mapping that export to the default property of the resolved module.

Example named export:

// Reports.jsx
export function Reports() {
  return <h2>Reports Page</h2>;
}

Lazy import of a named export:

import { lazy, Suspense } from "react";
const Reports = lazy(() =>
  import("./Reports.jsx").then((module) => ({
    default: module.Reports
  }))
);
function App() {
  return (
    <Suspense fallback={<p>Loading reports...</p>}>
      <Reports />
    </Suspense>
  );
}
export default App;

This approach adapts the named Reports export to the default export shape required by React.lazy.

12. Advantages of Code Splitting

  • Faster initial loading: Less JavaScript may need to be downloaded at startup.
  • On-demand loading: Additional features can load when users request them.
  • Better scalability: Large applications can be organized into independently loaded chunks.
  • Improved user experience: Users can begin interacting with the initial page without waiting for every optional feature.
  • Efficient resource use: Users may avoid downloading code for features they never access.
  • Flexible loading states: Suspense allows developers to display suitable placeholders during component loading.

13. Limitations and Challenges of Code Splitting

  • Additional network requests: Separate chunks may require additional requests when needed.
  • Loading delays: A component may take time to appear when its code is requested for the first time.
  • More complex error handling: A failed chunk request needs a suitable recovery strategy.
  • Bundle planning: Poor splitting choices can create too many small chunks or leave the initial bundle too large.
  • Loading-state design: Fallback interfaces should avoid confusing or disruptive transitions.
  • Configuration considerations: The bundler and deployment setup must support dynamic imports and serve generated chunks correctly.

14. Best Practices for Code Splitting

  1. Start with route-level Code Splitting for applications with many pages.
  2. Lazy-load large or optional components such as charts, rich text editors, maps, and complex dialogs.
  3. Use Suspense boundaries at appropriate points in the interface.
  4. Provide meaningful loading fallbacks, such as skeleton screens or concise loading messages.
  5. Avoid splitting every tiny component because excessive splitting can introduce unnecessary overhead.
  6. Keep frequently used code in the initial bundle when loading it immediately improves the user experience.
  7. Analyze production bundles to identify large dependencies and potential splitting opportunities.
  8. Handle lazy-loading failures with an Error Boundary and a retry or refresh option when appropriate.
  9. Test loading behavior on slower networks and smaller devices.
  10. Verify that generated chunks are available at the correct URLs in production.

15. Error Handling for Lazy-Loaded Components

Suspense handles the loading state while a lazy component is waiting for its code. It does not, by itself, provide a complete user-facing recovery interface for a failed dynamic import. A React Error Boundary can handle rendering errors, including rejected lazy imports.

Example:

import React, { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./Dashboard.jsx"));
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError() {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return <p>Unable to load this section. Please try again.</p>;
    }
    return this.props.children;
  }
}
function App() {
  return (
    <ErrorBoundary>
      <Suspense fallback={<p>Loading dashboard...</p>}>
        <Dashboard />
      </Suspense>
    </ErrorBoundary>
  );
}
export default App;

Explanation: Suspense displays the loading message while the component is loading. If the lazy import rejects, the Error Boundary can display an error message instead of leaving the user with a broken section. A production application may also provide a retry or page-refresh action.

16. Code Splitting vs Lazy Loading

Feature Code Splitting Lazy Loading
Meaning Divides code into separate bundles or chunks. Defers loading a resource until it is needed.
Purpose Creates separate loading units. Controls when those resources are loaded.
React example Dynamic imports recognized by the bundler. React.lazy with Suspense.
Relationship Provides the chunks that can be loaded separately. Loads a component's code on demand when used with dynamic imports.

17. Common Mistakes in Code Splitting

  • Forgetting Suspense: Lazy-loaded components should be rendered beneath an appropriate Suspense boundary.
  • Using the wrong export: React.lazy expects a module with a default component export unless the named export is adapted.
  • Declaring lazy components inside another component: Define lazy components at the module's top level to avoid unexpected state resets.
  • Splitting every component: Excessive splitting can add network overhead and complexity.
  • Ignoring errors: Dynamic imports can fail because of network problems or unavailable chunk files.
  • Using static imports accidentally: A static import may cause code to be included in a bundle that loads earlier than intended.
  • Ignoring the production build: Check actual generated chunks rather than assuming every import creates a separate file.

18. Practical Project: Lazy-Loaded Admin Dashboard

Objective: Build a simple application with Home and Admin Dashboard sections. Load the dashboard only when the user opens it.

File structure:

src/
├── App.jsx
├── main.jsx
└── AdminDashboard.jsx

AdminDashboard.jsx

export default function AdminDashboard() {
  return (
    <section>
      <h2>Admin Dashboard</h2>
      <p>Manage users, reports, and application settings.</p>
    </section>
  );
}

App.jsx

import { lazy, Suspense, useState } from "react";
const AdminDashboard = lazy(() => import("./AdminDashboard.jsx"));
function App() {
  const [open, setOpen] = useState(false);
  return (
    <main>
      <h1>Admin Portal</h1>
      <p>Welcome to the application home page.</p>
      <button onClick={() => setOpen(true)}>
        Open Admin Dashboard
      </button>
      {open && (
        <Suspense fallback={<p>Loading admin dashboard...</p>}>
          <AdminDashboard />
        </Suspense>
      )}
    </main>
  );
}
export default App;

Expected outcome: The home page appears first. When the user opens the dashboard, React requests the lazy-loaded component if it has not already been loaded. A loading message may appear before the dashboard is displayed.

Practice tasks:

  • Add a lazy-loaded Reports component.
  • Create a Settings component and load it when a button is clicked.
  • Replace the loading text with a reusable Loading component.
  • Add an Error Boundary for failed chunk requests.
  • Inspect the production build to see how the bundler creates chunks.

19. Interview Questions and Answers

Q1. What is Code Splitting in React?

Answer: Code Splitting is a technique that divides application code into separate bundles or chunks so that code can be loaded when needed instead of loading everything initially.

Q2. Why is Code Splitting useful?

Answer: It can reduce the initial JavaScript payload, improve loading performance, and defer optional features until users need them.

Q3. What is React.lazy()?

Answer: React.lazy() declares a component that React can load on demand using a dynamic import.

Q4. What is Suspense?

Answer: Suspense displays a fallback interface while its children are waiting for a supported resource, such as a lazy-loaded component's code.

Q5. What is a dynamic import?

Answer: The import() syntax loads a module asynchronously and returns a Promise that resolves to the module.

Q6. What is route-based Code Splitting?

Answer: Route-based Code Splitting separates page components so that their code can load when the corresponding routes are visited.

Q7. Does Code Splitting reduce the total amount of application code?

Answer: Not necessarily. It primarily changes how code is divided and loaded. It can reduce the amount of code downloaded initially, even when the total code remains the same.

Q8. Can React.lazy() load a named export directly?

Answer: React.lazy() expects a default export. A named export can be adapted using a Promise's then() method to return an object with a default property.

Q9. What happens if a lazy-loaded component fails to load?

Answer: The rejected import can be handled by an Error Boundary. The application should provide a useful error message and, where appropriate, a retry or refresh option.

Q10. Where should lazy components be declared?

Answer: Declare lazy components at the top level of the module rather than inside another component.

20. Summary

Code Splitting is an important performance technique for modern React applications. It divides application code into smaller chunks and allows features or pages to load when required. Dynamic imports, React.lazy(), and Suspense work together to enable on-demand component loading and provide useful loading states. Route-level splitting, sensible component boundaries, meaningful fallbacks, and appropriate error handling help developers build efficient and scalable React applications.

21. Learn React JS with JustAcademy

Learn React components, Hooks, routing, performance optimization, Code Splitting, and modern front-end development through structured training and practical projects.

JustAcademy React JS Training

Explore the course and register for a demo session using the link below.

Register for React JS Course Demo

Previous Next
whatsapp