Code Splitting and Lazy Loading in React :👈 👉:React Compiler: What Developers Should Understand

How to Use Suspense and Lazy Loading

How to Use Suspense and Lazy Loading in React

1. What Is Lazy Loading?

Lazy loading is a technique in which a component, JavaScript module, or other resource is loaded only when it is required instead of loading everything when the application starts.

Consider an application with the following pages:

  • Home
  • Products
  • Orders
  • Reports
  • Settings

When a user opens the Home page, there is no need to immediately download the JavaScript required for the Reports and Settings pages.

Lazy loading allows these components to be downloaded when the user navigates to them.

Without Lazy Loading

Traditional Bundle Loading Application Starts Load All Components Home Products Orders Reports Settings Display Application

With Lazy Loading

Lazy Loading Workflow Application Starts Load Home Component User Opens Reports Load Reports Component Display Reports

Benefits:

  • Reduces initial JavaScript loading.
  • Improves initial application startup.
  • Avoids downloading unnecessary components.
  • Useful for large applications with multiple pages.

2. What Is React Suspense?

Suspense is a React feature that allows you to display fallback content while a supported child component or resource is loading.

For example, when a user opens the Reports page, the JavaScript file may take some time to download.

Instead of displaying an empty screen, Suspense can display:

  • Loading...
  • Please wait...
  • Loading spinner
  • Skeleton UI

Once the component is ready, React displays the actual content.

Basic Syntax

import { Suspense } from "react";
function App() {
    return (
        <Suspense fallback={<p>Loading...</p>}>
            <MyComponent />
        </Suspense>
    );
}

Important: Suspense does not automatically make an ordinary component load asynchronously. It works with components and data sources that support Suspense.

3. Difference Between Suspense and Lazy Loading

Feature Lazy Loading Suspense
Purpose Delays loading until required. Displays fallback UI while waiting.
Function Controls when a component is loaded. Controls what the user sees while loading.
React API React.lazy Suspense
Code splitting Can create separate JavaScript chunks through dynamic imports. Does not create chunks by itself.
Example Load Reports when the user opens it. Display Loading Reports while it downloads.

Simple explanation:

  • Lazy Loading: Decides when to load a component.
  • Suspense: Decides what to display while the component is loading.

4. How to Use React.lazy with Suspense

React provides the lazy() function to dynamically import components.

React.lazy expects a function that returns a Promise resolving to a module with a default export.

Example

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

Reports.jsx

function Reports() {
    return (
        <div>
            <h2>Reports Page</h2>
            <p>Monthly sales reports.</p>
        </div>
    );
}
export default Reports;

How It Works

  1. React.lazy defines the Reports component as a lazy-loaded component.
  2. When React attempts to render Reports, the dynamic import starts.
  3. While the JavaScript module is downloading, the component suspends.
  4. Suspense displays the Loading Reports message.
  5. After the module loads, React renders the Reports component.

5. Practical Example: Load a Component on Button Click

Sometimes a component is needed only when the user performs a particular action.

For example, a Dashboard may contain an optional Analytics section.

Dashboard.jsx

import React, {
    lazy,
    Suspense,
    useState
} from "react";
const Analytics = lazy(
    () => import("./Analytics")
);
function Dashboard() {
    const [showAnalytics, setShowAnalytics] = useState(false);
    return (
        <div>
            <h2>Dashboard</h2>
            <p>Welcome to the Dashboard.</p>
            <button
                onClick={() => setShowAnalytics(true)}
            >
                View Analytics
            </button>
            {showAnalytics && (
                <Suspense fallback={<p>Loading Analytics...</p>}>
                    <Analytics />
                </Suspense>
            )}
        </div>
    );
}
export default Dashboard;

Analytics.jsx

function Analytics() {
    return (
        <div>
            <h3>Analytics Report</h3>
            <p>Display charts and business metrics here.</p>
        </div>
    );
}
export default Analytics;

What happens?

  1. Dashboard loads initially.
  2. Analytics is not initially rendered.
  3. The user clicks View Analytics.
  4. React attempts to render Analytics.
  5. The Analytics JavaScript module is downloaded.
  6. Suspense displays the loading message until the module is ready.

6. Route-Based Lazy Loading with React Router

For large React applications, route-based lazy loading is one of the most useful approaches.

Each page can be loaded independently when the user navigates to it.

Project Structure

src/
 |
 +---- pages/
 |       |
 |       +---- Home.jsx
 |       +---- Products.jsx
 |       +---- Reports.jsx
 |
 +---- App.jsx
 +---- main.jsx

App.jsx

import React, { lazy, Suspense } from "react";
import {
    BrowserRouter,
    Routes,
    Route,
    Link
} from "react-router-dom";
const Home = lazy(() => import("./pages/Home"));
const Products = lazy(() => import("./pages/Products"));
const Reports = lazy(() => import("./pages/Reports"));
function App() {
    return (
        <BrowserRouter>
            <nav>
                <Link to="/">Home</Link> |
                <Link to="/products">Products</Link> |
                <Link to="/reports">Reports</Link>
            </nav>
            <Suspense fallback={<p>Loading Page...</p>}>
                <Routes>
                    <Route
                        path="/"
                        element={<Home />}
                    />
                    <Route
                        path="/products"
                        element={<Products />}
                    />
                    <Route
                        path="/reports"
                        element={<Reports />}
                    />
                </Routes>
            </Suspense>
        </BrowserRouter>
    );
}
export default App;

Now the application loads the corresponding page component when the user visits that route.

Loading Behavior

User Action Component Loaded
Open Home Home.jsx
Navigate to Products Products.jsx
Navigate to Reports Reports.jsx

7. Using Multiple Suspense Boundaries

You do not have to use only one Suspense boundary for the entire application.

You can create multiple boundaries for different parts of the UI.

This is useful when one part of a page loads independently of another.

Example

import React, { lazy, Suspense } from "react";
const UserProfile = lazy(
    () => import("./UserProfile")
);
const Analytics = lazy(
    () => import("./Analytics")
);
function Dashboard() {
    return (
        <div>
            <h2>Dashboard</h2>
            <Suspense fallback={<p>Loading Profile...</p>}>
                <UserProfile />
            </Suspense>
            <Suspense fallback={<p>Loading Analytics...</p>}>
                <Analytics />
            </Suspense>
        </div>
    );
}
export default Dashboard;

Each section can display its own loading indicator.

Benefit: A slow Analytics component does not necessarily need to prevent the Profile section from appearing.

8. Using Suspense with API Data Loading

Suspense can also be used for data loading, but ordinary fetch() calls inside useEffect do not automatically activate Suspense.

For example, the following approach does not automatically suspend:

useEffect(() => {
    fetch("/api/products")
        .then(response => response.json())
        .then(data => setProducts(data));
}, []);

For Suspense-based data loading, use a framework or data-fetching library that explicitly supports Suspense, or an appropriate Suspense-compatible data source.

Example Using a Framework with Suspense Support

Some React frameworks provide built-in Suspense integration for data fetching and server rendering.

For example, a framework can render a component that reads data through a Suspense-compatible mechanism:

import { Suspense } from "react";
function ProductPage() {
    return (
        <Suspense fallback={<p>Loading products...</p>}>
            <ProductList />
        </Suspense>
    );
}

Here, ProductList must use a data-loading mechanism that actually supports Suspense. The Suspense boundary alone does not make a normal API request suspend.

9. Suspense with React Error Boundaries

Suspense handles loading states, but it does not handle errors when a lazy-loaded component fails to download.

Use an Error Boundary to display a fallback UI when a component fails during rendering or loading.

ErrorBoundary.jsx

import React from "react";
class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            hasError: false
        };
    }
    static getDerivedStateFromError(error) {
        return {
            hasError: true
        };
    }
    render() {
        if (this.state.hasError) {
            return (
                <p>Unable to load this component.</p>
            );
        }
        return this.props.children;
    }
}
export default ErrorBoundary;

Using Error Boundary with Suspense

import React, { lazy, Suspense } from "react";
import ErrorBoundary from "./ErrorBoundary";
const Reports = lazy(
    () => import("./Reports")
);
function App() {
    return (
        <ErrorBoundary>
            <Suspense fallback={<p>Loading Reports...</p>}>
                <Reports />
            </Suspense>
        </ErrorBoundary>
    );
}
export default App;

Difference:

Feature Purpose
Suspense Displays fallback content while waiting for supported loading operations.
Error Boundary Displays fallback UI when a descendant throws an error during rendering.

Important: Error Boundaries do not automatically retry a failed import. A retry strategy may require resetting the boundary and retrying the import, or reloading the application when appropriate.

10. How to Display a Better Loading UI

Instead of displaying only a text message, you can create a reusable loading component.

Loading.jsx

function Loading() {
    return (
        <div>
            <h3>Please wait...</h3>
            <p>Loading application content.</p>
        </div>
    );
}
export default Loading;

Using It

import React, { lazy, Suspense } from "react";
import Loading from "./Loading";
const Reports = lazy(
    () => import("./Reports")
);
function App() {
    return (
        <Suspense fallback={<Loading />}>
            <Reports />
        </Suspense>
    );
}

This approach allows the same loading component to be reused throughout the application.

11. Important Rules and Limitations

  1. React.lazy requires a dynamic import that resolves to a module with a default export.
  2. A lazy component must be rendered within a Suspense boundary.
  3. Suspense does not automatically handle ordinary fetch() calls inside useEffect.
  4. Suspense does not handle errors; use an Error Boundary.
  5. Lazy loading is most useful for routes and large optional components.
  6. Do not lazy-load every small component.
  7. Use meaningful loading indicators to improve the user experience.
  8. Code splitting reduces initial downloads, but does not necessarily reduce the total application code.

12. Best Practices

  1. Use route-based lazy loading for large applications.
  2. Use React.lazy for components that are not immediately required.
  3. Wrap lazy-loaded components with Suspense.
  4. Use separate Suspense boundaries when independent page sections need independent loading states.
  5. Provide reusable loading indicators.
  6. Use Error Boundaries to handle loading failures.
  7. Lazy-load large libraries such as PDF generators and charting tools.
  8. Consider prefetching frequently accessed routes.
  9. Avoid excessive code splitting.
  10. Measure production bundle size and loading performance after optimization.

13. Interview Questions and Answers

Q1. What is React Suspense?

Suspense is a React feature that allows a component tree to display fallback content while a supported child component or resource is loading.

Q2. What is React.lazy?

React.lazy allows components to be imported dynamically instead of being included in the initial JavaScript bundle.

Q3. Why do we use Suspense with React.lazy?

React.lazy loads components asynchronously. Suspense provides a fallback UI while the component's JavaScript module is downloading.

Q4. Can Suspense handle API calls made using useEffect?

No. Ordinary API calls inside useEffect do not automatically activate Suspense. A Suspense-compatible data-fetching mechanism is required.

Q5. Can we use multiple Suspense boundaries?

Yes. Multiple Suspense boundaries allow different sections of an application to display independent loading indicators.

Q6. What happens if a lazy-loaded component fails?

The dynamic import rejects. A React Error Boundary can catch the resulting rendering error and display fallback UI.

Q7. What is the difference between Suspense and an Error Boundary?

Suspense handles loading states for supported resources, whereas Error Boundaries handle errors thrown by descendant components during rendering and related lifecycle operations.

Q8. Does Suspense perform code splitting?

No. Suspense itself does not create JavaScript chunks. Dynamic imports and build tools provide code splitting, while Suspense handles the loading UI.

Q9. Can we lazy-load a component on button click?

Yes. Use React.lazy to define the component and conditionally render it after the user clicks the button. React then loads the component when it is first rendered.

Q10. When should you use Suspense?

Use Suspense when working with lazy-loaded components or other Suspense-compatible features that need a fallback UI while loading.

14. Quick Summary

Concept Purpose
Lazy Loading Load components only when required.
React.lazy Dynamically import React components.
Suspense Display fallback UI while loading.
Dynamic import() Load JavaScript modules asynchronously.
Route-based loading Load pages when users navigate to them.
Multiple Suspense boundaries Display independent loading indicators for different sections.
Error Boundary Handle component loading and rendering errors.
Suspense-compatible data fetching Allow supported data sources to suspend while loading.

Key takeaway: React.lazy is used to load components dynamically, while Suspense displays fallback content until those components are ready. Together, they help implement lazy loading, route-based code splitting, and a better loading experience in large React applications.

🔙
Code Splitting and Lazy Loading in React :👈 👉:React Compiler: What Developers Should Understand

Comments and Discussion