Preloading Lazy Components on Hover
You'll learn: How to start loading lazy-loaded components before navigation happens, creating instant-feeling transitions by preloading on user interaction like hover.
The Problem with Waiting
When you use React.lazy(), components only start downloading when React tries to render them. This means users see a spinner after they click a link. Even a half-second delay feels sluggish.
The good news? You can be proactive.
Calling import() Early
Remember that React.lazy() wraps a dynamic import() function. Here's the trick: you can call that same import function yourself, outside of React, whenever you want.
When a user hovers over a navigation link, there's often a split second before they click. That's your window to start preloading:
const LazyDashboard = React.lazy(() => import('./Dashboard'));
function Navigation() {
const preloadDashboard = () => {
// Trigger the import early
import('./Dashboard');
};
return (
<nav>
<a
href="/dashboard"
onMouseEnter={preloadDashboard}
>
Dashboard
</a>
</nav>
);
}
When the user hovers, import() starts fetching the code. By the time they click, the component is already loaded (or nearly so). When React renders the lazy component, it finds the module ready and skips the fallback entirely.
Think of It Like This
It's like opening your car door while walking toward it — by the time you're ready to sit down, the door's already open. You didn't wait for the moment of need.
Key Takeaway: Preload lazy components on hover or other early interactions by calling import() directly, so the code is ready before navigation — turning lazy loading from sluggish to instant.