React › Code Splitting & Lazy Loading
How would you preload a lazy loaded component before the user actually navigates to it?
AdvancedAnswer
You can call the same dynamic import function used inside React.lazy ahead of time, such as when the user hovers over a link, so the code is already downloaded and ready by the time they click. This makes navigation feel instant instead of showing a loading spinner.
const loadDashboard = () => import('./Dashboard');
const Dashboard = React.lazy(loadDashboard);
function NavLink() {
return (
<a href="/dashboard" onMouseEnter={loadDashboard}>
Dashboard
</a>
);
}Real-world example A news website preloads the code for an article page as soon as a reader hovers their mouse over the headline, so clicking the link feels instant instead of showing a brief loading delay.