Sub topic 9
Preloading components before they are needed
Lazy loading trades a smaller first download for a delay later. When a user clicks a link to a lazy component, the browser must fetch the chunk first, and the fallback shows during that wait. Preloading removes much of that delay by starting the download before the component renders. This chapter shows how preloading works with React.lazy, when to trigger it, and where it goes wrong.
This chapter assumes you know how React.lazy, Suspense and dynamic import() work, and that you can read basic event handlers and promises.
Why preloading works
Calling import('./Settings') does two things. It starts a network request for the chunk, and it returns a promise. The bundler (Vite, webpack, or similar) and the browser keep the result of that request. If the same specifier is imported again, the second call returns the same module instead of downloading it again.
React.lazy calls your loader function the first time the component renders. That call is just another import(). If the chunk was already requested, lazy gets the cached module, often right away. The user sees no fallback, or only a very short one.
So preloading is a small idea: call the same import function earlier than React would.
The basic pattern
Define the loader function once, with a name. Pass it to lazy, and call it yourself when you want an early download.
import { lazy } from 'react';
const loadSettings = () => import('./Settings');
const Settings = lazy(loadSettings);
export function SettingsLink({ onOpen }) {
return (
<button onMouseEnter={loadSettings} onFocus={loadSettings} onClick={onOpen}>
Settings
</button>
);
}Three details matter here.
- The loader is a named function, not an inline arrow inside
lazy(...). You need a reference to call it from elsewhere. loadSettingsreturns a promise, and the event handler ignores it. That is fine. The goal is the side effect of starting the request.- Both
onMouseEnterandonFocusare used. Hover helps mouse users. Focus covers keyboard users, who never hover.
What the cache actually guarantees
React does not cache the chunk. Your bundler's runtime and the browser do. In practice:
- Vite and other native ES module setups rely on the browser's module map. A given URL is fetched and evaluated once per page.
- webpack keeps its own record of loaded chunks and reuses the pending promise for a chunk that is still downloading.
This means that calling loadSettings many times is safe. Repeated calls do not trigger repeated downloads. It also means the guarantee comes from the tooling, so test it in your own build rather than assuming it.
Choosing when to preload
Each trigger is a guess about what the user will do next. A stronger signal gives a more accurate guess but leaves less time to download.
| Trigger | Signal strength | Lead time | Typical use |
|---|---|---|---|
| Hover or focus on a link | Medium | Often 100 to 300 ms | Navigation links, menu items |
| Pointer down (before click completes) | High | Very short | Buttons where hover is not available |
| Link enters the viewport | Low | Seconds | Long pages with many links |
| Browser is idle after first render | Low | Long | Pages most users visit next |
| After a prior step in a flow | High | Varies | Checkout step 2 after step 1 |
Hover gives a head start of only a few hundred milliseconds. A small chunk on a fast connection may finish in that time. A large chunk on a slow one will not. In that case the fallback still appears, but the wait is shorter than it would have been.
Touch screens have no hover. For them, onPointerDown or onTouchStart is the earliest useful event, and the head start is only the time between press and release.
Preloading on idle
Some destinations are so likely that you can fetch them without any user signal. After the first page has rendered and the browser is quiet, start the download.
import { lazy, useEffect } from 'react';
const loadReports = () => import('./Reports');
const Reports = lazy(loadReports);
export function useIdlePreload(load) {
useEffect(() => {
const run = () => load();
if ('requestIdleCallback' in window) {
const id = window.requestIdleCallback(run);
return () => window.cancelIdleCallback(id);
}
const id = window.setTimeout(run, 2000);
return () => window.clearTimeout(id);
}, [load]);
}
export function Home() {
useIdlePreload(loadReports);
return <a href="/reports">Reports</a>;
}requestIdleCallback runs the function when the browser has spare time. Safari did not support it for a long time, so the code falls back to a timer. Pass a stable load function, defined outside the component, so the effect does not re-run on every render.
Idle preloading spends the user's bandwidth on code they may never use. On a metered mobile connection, that cost is real. Reserve it for destinations that most users reach.
Preloading in the bundler
You can also hint at chunks in the build, without any React code. Webpack supports magic comments inside import():
const loadReports = () =>
import(/* webpackPrefetch: true */ './Reports');webpackPrefetch makes webpack add a <link rel="prefetch"> after the parent chunk loads. The browser fetches the file at low priority during idle time. webpackPreload instead asks for the chunk at medium priority in parallel with the parent, which is for chunks needed almost immediately.
Vite does not use these comments. It already adds modulepreload links for the static imports of a chunk. For a dynamic import you control the timing yourself, as in the patterns above.
Prefetch is a hint. The browser may delay or skip it, for example on a slow connection with data saver enabled.
Preloading with a router
Route-based splitting benefits the most from preloading, because routes are the most common lazy boundaries. A simple approach is to keep a map from route paths to loader functions and reuse it for both lazy and the link.
import { lazy } from 'react';
import { Link } from 'react-router-dom';
const routes = {
'/': () => import('./pages/Home'),
'/settings': () => import('./pages/Settings'),
};
export const Home = lazy(routes['/']);
export const Settings = lazy(routes['/settings']);
export function PreloadLink({ to, children }) {
const preload = () => routes[to]?.();
return (
<Link to={to} onMouseEnter={preload} onFocus={preload}>
{children}
</Link>
);
}This keeps one source of truth. Adding a route means adding one entry, and the link preloads it without extra work.
Some routers, including React Router's data APIs and TanStack Router, have built-in options to preload on link intent. If your router has one, prefer it, because it can also preload the route's data and not only its code.
Preloading and Suspense together
Preloading changes timing, but the Suspense contract stays the same. A preloaded component still needs a Suspense boundary above it. Three outcomes are possible when the component renders:
- The chunk has fully loaded.
lazyresolves immediately and no fallback appears. - The chunk is still downloading.
lazysuspends and the fallback shows until it finishes. - The download failed. The promise rejects and an error boundary must handle it.
Never remove the Suspense or the error boundary because "it is always preloaded". Preloading is an optimization, not a guarantee.
A related trick is to combine preloading with transitions. If a click starts a state change that renders the lazy component, wrapping it in startTransition keeps the old screen visible while the remaining bytes arrive. The earlier chapter on transitions covers this. The two techniques cover different parts of the delay: preloading shortens it, and transitions hide what is left.
A reusable preloadable wrapper
Passing around a lazy component and a separate loader gets tedious. A small helper bundles them.
import { lazy } from 'react';
export function lazyWithPreload(loader) {
const Component = lazy(loader);
Component.preload = loader;
return Component;
}
const Settings = lazyWithPreload(() => import('./Settings'));
export function SettingsLink({ onOpen }) {
return (
<button
onMouseEnter={() => Settings.preload()}
onFocus={() => Settings.preload()}
onClick={onOpen}
>
Settings
</button>
);
}lazy returns an object, so adding a property to it is allowed. It is a convention, not a React API, so a future React version could in principle change that object. Many teams use it anyway. The explicit pair of loader and lazy(loader) shown earlier is the safer choice if you want to avoid relying on it.
Pitfalls
Preloading everything
If every link preloads on viewport entry, the app downloads most of its chunks soon after load. That undoes the savings from splitting and competes with the data and scripts the current page needs. Preload only the likely next steps.
Unhandled rejections
When a preload fails, the returned promise rejects. Because your handler ignores the promise, the browser logs an "unhandled promise rejection" in the console, and error monitoring tools may report it. Catch it on purpose:
const loadSettings = () => import('./Settings');
export function preloadSettings() {
loadSettings().catch(() => {
// Ignore. React will try again when the component renders.
});
}Does a failed preload break the later render? In most bundlers a rejected import() can be retried, and webpack clears its failed-chunk record so a later call tries again. Native module loading in some browsers can cache a failure for the same URL for the page's lifetime, so a retry may fail the same way. Keep the error boundary in place and offer a reload as the recovery.
Preloading on the server
Event handlers and effects only run in the browser, so these patterns do nothing during server rendering. That is expected. The server has no hover. Do not call window functions at module top level in a file that also runs on the server.
Cache invalidation after a deploy
A preloaded chunk file name usually contains a content hash. If you deploy a new version while a user has the old page open, the old chunk URL may disappear and the preload returns a 404. This is the same failure the error boundary chapter covers, and a preload can trigger it earlier than the render would.
Verifying that it helps
Check the effect with measurement rather than guessing.
- Open the browser's developer tools and select the Network tab.
- Throttle the connection to a profile such as "Fast 4G".
- Hover over the link. Confirm that the chunk request starts at hover, not at click.
- Click. Confirm that no second request for that chunk appears, and that the fallback does not show.
- Repeat without preloading and compare the time between click and visible content.
Watch for a request that appears twice, which means the loader specifier differs between the preload and the lazy call. Both must point to the same module path.
Summary of the decisions
Use a named loader function shared by lazy and the trigger. Start with hover and focus on navigation links. Add idle preloading only for very likely destinations. Keep Suspense and an error boundary in place. Confirm in the Network tab that the chunk is requested once, early.
Exercise
A teammate writes const Settings = lazy(() => import('./Settings')); and, in a link component, onMouseEnter={() => import('./Settings')}. The preload seems to work. Name one risk of this setup and show how you would change it.
Show answer
The two import('./Settings') calls are separate strings that can drift apart, for example after a file rename or when only one is updated, so the preload could fetch a different module than the one lazy renders. Define one loader, const loadSettings = () => import('./Settings');, then use lazy(loadSettings) and onMouseEnter={loadSettings} (and onFocus={loadSettings} for keyboard users). Both now share one specifier, and the bundler's module cache lets lazy reuse the downloaded chunk.
Exercise
Why is it still necessary to wrap a preloaded lazy component in Suspense and an error boundary?
Show answer
Preloading only starts the download early. When the component renders, the chunk may still be downloading, so lazy suspends and needs a Suspense fallback. The download may also have failed, for example from a network error or a missing chunk after a deploy, so the promise can reject and needs an error boundary. Preloading shortens the wait but does not guarantee success.
Exercise
Your app has 30 links. A developer proposes preloading every linked page's chunk as soon as the home page finishes rendering. Give two reasons this might hurt, and one better approach.
Show answer
First, it downloads chunks most users never open, which wastes bandwidth and can cost metered mobile users money. Second, those downloads compete with data and scripts the current page needs, which can slow it down and cancels much of the benefit of splitting. A better approach is to preload on user intent (hover, focus, pointer down) for all links, and use idle preloading only for the one or two destinations most users visit next.