Menu

Lazy Loading and Code Splitting

Lazy Loading and Code Splitting

What is Code Splitting?

By default, the build produces one JavaScript bundle containing your entire application. A user landing on the homepage downloads the admin panel, the settings page, and everything else before anything appears.

Code splitting breaks the bundle into pieces that load on demand.

Syntax

jsx

import { lazy, Suspense } from "react";

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

Example

src/App.jsx

jsx

import { lazy, Suspense } from "react";
import { Routes, Route } from "react-router-dom";
import Navbar from "./components/Navbar";
import Home from "./pages/Home";

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

function App() {
  return (
    <div>
      <Navbar />
      <Suspense fallback={<p>Loading page...</p>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/courses" element={<Courses />} />
          <Route path="/dashboard" element={<Dashboard />} />
        </Routes>
      </Suspense>
    </div>
  );
}

export default App;

How It Works

  • lazy(() => import("./pages/Dashboard")) tells the build tool to put Dashboard in its own file, downloaded only when that route is visited.
  • <Suspense fallback={...}> is required. It shows the fallback while the chunk downloads.
  • Home is imported normally because it is needed immediately; lazy-loading it would only add a delay.

Route-level splitting like this is the highest-value place to start. Splitting individual small components rarely pays off.


ReactJS Tutorial

VA

Vishalini A



Learn via Video Course

React.js for Beginners: Build Modern Web Applications with React Logo

React.js for Beginners: Build Modern Web Applications with React

6 hrs



Get in Touch For Details