Course contentsShow
← React
Lesson 1407 of 2,39635. Code SplittingFree lesson

Modal and Dialog Lazy Loading

Defer loading modal content until the user opens it, a classic high-impact code splitting win.

Modal and Dialog Lazy Loading

You'll learn how to slash your initial bundle size by deferring modal components until users actually open them.

Modals and dialogs are perfect code-splitting candidates: they're hidden by default, often contain heavy UI (forms, charts, media), and might never be opened during a visit. Loading them upfront wastes bandwidth and slows down your page's initial render.

Why Modals Are Ideal for Lazy Loading

Think of modals like tools in a toolbox. You don't carry every tool everywhere — you grab the wrench when you need it. Similarly, modal components should only load when the user triggers them (button click, menu action, etc.).

The win is substantial: modals often import rich libraries (date pickers, WYSIWYG editors, charting tools) that can add hundreds of KB to your main bundle.

The Pattern

Instead of importing your modal component at the top of your file, use React.lazy() and trigger the load when the user clicks "Open Modal":

const HeavyModal = React.lazy(() => import('./HeavyModal'));

function App() {
  const [isOpen, setIsOpen] = useState(false);

  return (
    <>
      <button onClick={() => setIsOpen(true)}>Open Settings</button>
      
      {isOpen && (
        <Suspense fallback={<div>Loading modal...</div>}>
          <HeavyModal onClose={() => setIsOpen(false)} />
        </Suspense>
      )}
    </>
  );
}

The modal chunk only downloads after isOpen becomes true. The Suspense boundary shows a loading state during the brief fetch.

Key Takeaway: Modal and dialog components are high-impact lazy loading targets — defer them until the user opens them to dramatically reduce your initial bundle size with minimal UX cost.