Lazy Loading on Click or Hover
What You'll Learn
You'll learn how to trigger React.lazy() imports inside event handlers, delaying the download of code until a user actually interacts with a UI element.
The Core Idea
Instead of lazy-loading components when they first render, you can wait until a user hovers over a button or clicks a menu item. This approach shrinks your initial bundle even further by deferring code that users might never need.
The pattern works by calling the dynamic import() inside an onClick or onMouseEnter handler. You can store the result in state or simply trigger the import early so it's ready when the component actually mounts.
How It Works
const [showModal, setShowModal] = React.useState(false);
// Preload on hover
const preloadModal = () => {
import('./HeavyModal'); // triggers download, doesn't render yet
};
// Show on click
const handleClick = () => {
setShowModal(true); // Now React.lazy() kicks in
};
return (
<>
<button
onClick={handleClick}
onMouseEnter={preloadModal}
>
Open Settings
</button>
{showModal && (
<Suspense fallback={<Spinner />}>
<LazyModal />
</Suspense>
)}
</>
);
Here, hovering starts the download, and clicking renders the component. If the user hovers long enough, the modal appears instantly when clicked—no spinner needed.
The Benefit
This technique is ideal for features like modals, dropdowns, admin panels, or help widgets that users access occasionally. Your main bundle stays lean, and engaged users still get fast experiences because the code arrives before they finish clicking.
Analogy
Think of a restaurant menu with a "Chef's Surprise" item. The kitchen doesn't prepare it until you hover over the name (preload), and only serves it when you actually order (click). No wasted prep for dishes no one orders.
Key Takeaway: Lazy load components on user interaction by triggering import() in event handlers, reducing your initial bundle while keeping interactive features fast for engaged users.