React js Lazy Loading and Suspense Practice Questions with Solutions

Introduction

Lazy Loading allows a React application to load a component only when it is needed instead of loading everything in the initial JavaScript bundle. React provides lazy() for defining a lazily loaded component and Suspense for displaying fallback UI while that component is loading. This can improve the initial loading experience, especially in larger applications. In this chapter, we will solve practical questions about lazy(), Suspense, fallback UI, routes, and common usage patterns. React js Lazy Loading and Suspense Practice Questions to help you understand the concepts.

1. What is Lazy Loading in React?

Answer:

Lazy Loading means loading a component only when it is required instead of loading it immediately when the application starts.

React provides the lazy() function for this purpose.

Example:

import { lazy } from "react";

const About = lazy(() => import("./About"));

Here, the About component is loaded dynamically when React needs to render it.

This can help reduce the amount of JavaScript that needs to be loaded initially.


2. How Do You Use React.lazy()?

Answer:

lazy() accepts a function that returns a Promise, usually created with a dynamic import().

Example:

import { lazy } from "react";

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

function App() {
  return <Dashboard />;
}

export default App;

The important part is:

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

React will load the Dashboard module when the lazy component is first rendered.


3. What is Suspense in React?

Answer:

Suspense allows React to display fallback UI while a component that can suspend is not ready to render.

For a lazy-loaded component:

import { lazy, Suspense } from "react";

const About = lazy(() => import("./About"));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <About />
    </Suspense>
  );
}

export default App;

While About is loading, React displays:

Loading...

After the component becomes available, React displays the About component.


4. How Do You Create a Lazy-Loaded Component With a Loading Message?

Answer:

Use lazy() together with Suspense.

import { lazy, Suspense } from "react";

const Profile = lazy(() => import("./Profile"));

function App() {
  return (
    <Suspense fallback={<h2>Loading Profile...</h2>}>
      <Profile />
    </Suspense>
  );
}

export default App;

The fallback prop specifies what React should display while the lazy component is loading.

You can use any suitable React element as the fallback:

<Suspense fallback={<p>Loading...</p>}>

or:

<Suspense fallback={<div>Please wait...</div>}>


5. Can Suspense Wrap Multiple Lazy Components?

Answer:

Yes. A single Suspense boundary can wrap multiple components.

Example:

import { lazy, Suspense } from "react";

const About = lazy(() => import("./About"));
const Contact = lazy(() => import("./Contact"));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <About />
      <Contact />
    </Suspense>
  );
}

export default App;

If either component suspends while loading, the Suspense boundary can show its fallback.

For more control, you can also create separate Suspense boundaries:

<Suspense fallback={<p>Loading About...</p>}>
  <About />
</Suspense>

<Suspense fallback={<p>Loading Contact...</p>}>
  <Contact />
</Suspense>

This allows different parts of the UI to have different loading states.


6. How Can Lazy Loading Be Used With React Router?

Answer:

Lazy loading is commonly used with routes so that different pages are loaded when users navigate to them.

Example:

import { lazy, Suspense } from "react";
import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";

const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));
const Contact = lazy(() => import("./Contact"));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<p>Loading page...</p>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
          <Route path="/contact" element={<Contact />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

export default App;

This approach can split the application’s JavaScript into separate chunks so that page code does not all need to be loaded at the beginning.


7. Why Is Lazy Loading Useful for Large React Applications?

Answer:

Large applications can contain many components and pages.

Loading everything immediately can increase the initial JavaScript payload.

Lazy loading allows parts of the application to be loaded when they are needed.

For example:

Application
│
├── Home
├── About
├── Dashboard
├── Reports
└── Settings

Instead of loading every page’s code immediately, you can lazy-load less frequently used pages:

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

This can improve initial loading performance.

However, lazy loading is not automatically beneficial for every component. Very small or frequently used components may not need to be split into separate chunks.


8. What is the Difference Between lazy() and Suspense?

Answer:

lazy() and Suspense have different responsibilities.

lazy()

lazy() defines a component whose module is loaded dynamically.

const Profile = lazy(() => import("./Profile"));

Suspense

Suspense defines what UI should be displayed while something inside the boundary is suspended.

<Suspense fallback={<p>Loading...</p>}>
  <Profile />
</Suspense>

In simple terms:

lazy()     → Load the component when needed
Suspense   → Show fallback while it is waiting

They are commonly used together.


9. What Happens If a Lazy Component Fails to Load?

Answer:

Suspense handles the waiting state, but it is not an error handler.

If the lazy-loaded module fails to load, for example because of a network problem, an error can occur.

An Error Boundary can be used to handle rendering errors, including errors caused by failed lazy loading.

For example:

import { lazy, Suspense } from "react";

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

function App() {
  return (
    <ErrorBoundary>
      <Suspense fallback={<p>Loading Dashboard...</p>}>
        <Dashboard />
      </Suspense>
    </ErrorBoundary>
  );
}

The exact Error Boundary implementation depends on the application’s architecture.

The important distinction is:

Suspense      → Handles waiting/loading UI
Error Boundary → Handles rendering errors

Suspense should not be treated as a replacement for error handling.


10. Create a Practical React.js Lazy Loading and React Suspense Example

Answer:

Consider an application with three pages:

src/
│
├── App.jsx
├── Home.jsx
├── About.jsx
└── Contact.jsx

We can lazy-load the pages.

App.jsx

import { lazy, Suspense } from "react";

const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));
const Contact = lazy(() => import("./Contact"));

function App() {
  const [page, setPage] = useState("home");

  return (
    <div>
      <nav>
        <button onClick={() => setPage("home")}>
          Home
        </button>

        <button onClick={() => setPage("about")}>
          About
        </button>

        <button onClick={() => setPage("contact")}>
          Contact
        </button>
      </nav>

      <Suspense fallback={<h2>Loading...</h2>}>
        {page === "home" && <Home />}
        {page === "about" && <About />}
        {page === "contact" && <Contact />}
      </Suspense>
    </div>
  );
}

export default App;

The page components are loaded dynamically:

const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));
const Contact = lazy(() => import("./Contact"));

When a lazy component needs to load, the Suspense boundary displays:

Loading...

Once the component is ready, React displays the requested page.

This pattern is useful for larger applications where different sections do not need to be loaded immediately.

Key Takeaways

  • Lazy Loading loads code when it is needed instead of loading everything initially.
  • React provides lazy() for lazy-loaded components.
  • lazy() commonly works with dynamic import().
  • Suspense provides fallback UI while something inside the boundary is suspended.
  • fallback defines the loading UI.
  • Multiple lazy components can be wrapped in one Suspense boundary.
  • Separate Suspense boundaries can provide more granular loading states.
  • Lazy loading is commonly useful for route-level code splitting.
  • Suspense is not an Error Boundary.
  • Error Boundaries can handle errors from failed lazy loading.
  • Lazy loading should be used where it provides a practical performance benefit.
  • Smaller frequently used components may not always benefit from separate chunks.

FAQs

1. What is React.js Lazy Loading?

Lazy Loading means loading a component’s code only when that component is needed rather than loading it as part of the initial application code.

2. What is React Suspense used for?

Suspense lets React display fallback UI while a component inside the boundary is suspended.

3. Can React.lazy() work without Suspense?

A lazy component needs an appropriate Suspense boundary above it to provide fallback UI while it is loading.

4. What is the difference between React.js Lazy Loading Lazy Loading and code splitting?

Lazy loading is a way to defer loading code until it is needed. Code splitting is the process of dividing application code into separate chunks. React lazy() with dynamic import() is a common way to achieve component-level code splitting.

5. Can I use Suspense with React Router?

Yes. Suspense can wrap routes or individual route elements that are lazy-loaded.

6. Does React Suspense handle errors?

No. Suspense handles the suspended/loading state. Error Boundaries are used for handling rendering errors.

7. Should every React component be lazy-loaded?

No. Lazy loading adds separate chunks and loading boundaries. It is generally more useful for large pages, routes, or features that are not needed immediately than for every small component.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top