ReactEasy
What is lazy loading?
Lazy loading means loading code or resources only when they are needed instead of upfront. In React you lazy-load components with React.lazy(() => import("./X")) inside <Suspense>, load routes on demand, defer images with loading="lazy", and import heavy libraries inside event handlers.
Component lazy loading
const Chart = lazy(() => import("./Chart"))creates a separate chunk.- Render it inside
<Suspense fallback={...}>; the fallback shows while the chunk downloads. - Load on interaction: only render
<Chart />after the user opens a tab or modal.
Route-level
- Routers load each route's code when visited. React Router supports a
lazyfunction on route objects; Next.js splits per route automatically.
Other assets
- Images and iframes: native
loading="lazy". - Libraries:
const { jsPDF } = await import("jspdf")inside the click handler. - Data: fetch on scroll or visibility with
IntersectionObserver.
Avoiding slow interactions
- Prefetch likely chunks on hover or idle: call the same
import()early, since modules are cached. - Keep the fallback similar in size to the content to avoid layout shift.
- Do not lazy-load tiny components or above-the-fold content.
Errors
A failed chunk download (often after a new deployment) throws; wrap lazy components in an error boundary with a retry or reload option.
Code example
tsx
1import { lazy, Suspense, useState } from "react";23const importEditor = () => import("./rich-text-editor");4const RichTextEditor = lazy(importEditor);56export function Comments() {7 const [editing, setEditing] = useState(false);89 async function exportCsv() {10 const { unparse } = await import("papaparse"); // library loaded only on click11 console.log(unparse([{ id: 1, text: "Nice" }]));12 }1314 return (15 <section>16 <img src="/banner.jpg" alt="" loading="lazy" width={800} height={200} />17 <button18 onMouseEnter={importEditor} // prefetch the chunk on hover19 onClick={() => setEditing(true)}20 >21 Write a comment22 </button>23 <button onClick={exportCsv}>Export CSV</button>2425 {editing && (26 <Suspense fallback={<div style={{ height: 200 }}>Loading editor…</div>}>27 <RichTextEditor />28 </Suspense>29 )}30 </section>31 );32}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.