Back to roadmaps react Course

React.lazy and Suspense

In large React applications, bundle files can grow rapidly, slowing down initial page load times. Code Splitting allows you to split your bundle into multiple chunks that load dynamically only when they are needed.


1. What is Code Splitting?

Instead of downloading the entire application bundle on the initial visit, code splitting loads only the critical bundle resources required to display the home screen. Less critical bundles (like settings panels or dashboards) are loaded on-demand.


2. Using React.lazy

The React.lazy() function lets you render a dynamic import as a regular component. It takes a callback that returns a dynamic import promise:

import React from "react";

// Dynamically import the heavy component
const HeavyChart = React.lazy(() => import("./HeavyChart"));

3. Waiting with Suspense

A lazy-loaded component cannot be rendered immediately because the browser must fetch its bundle chunk from the network.

To prevent React from throwing errors during this loading window, you must wrap the lazy component inside a Suspense component. The Suspense component accepts a fallback prop, which takes a React node (like a loading spinner) to render while waiting for the chunk to load:

import React, { Suspense } from "react";

const HeavyChart = React.lazy(() => import("./HeavyChart"));

function Dashboard() {
  return (
    <div className="dashboard-container">
      <h1>Performance Report</h1>
      
      {/* Fallback spinner displays while chart chunk downloads */}
      <Suspense fallback={<div className="spinner">Loading chart...</div>}>
        <HeavyChart />
      </Suspense>
    </div>
  );
}

4. Route-Based Code Splitting

A best practice in React applications is to apply code splitting at the routing level (such as using React Router). This ensures that navigating to a new page loads only the bundle chunk required for that specific route:

import React, { Suspense } from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";

const Home = React.lazy(() => import("./routes/Home"));
const Settings = React.lazy(() => import("./routes/Settings"));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading Page...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </Router>
  );
}
Published on Last updated: