Sub topic 9
Preloading components before they are needed
This chapter assumes you can write function components, use useState, read ES module syntax, and already know how React.lazy and Suspense work together. It covers how to start downloading a lazy chunk before the user asks for it.
Why preload
A lazy component downloads when it first renders. If the user clicks "Settings" and the chunk is not loaded, they see the fallback until the download finishes. On a slow network that delay is visible.
Preloading starts the download earlier, at a moment when the user is likely to need the component soon. Good triggers include hovering over a link, focusing a button, or finishing the render of a related page. When the user finally clicks, the chunk is often already in the browser, and the component renders without a fallback.
The core technique
React.lazy takes a function that returns a promise from import(). You can keep that function in a variable, pass it to lazy, and also call it yourself.
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>
);
}Calling loadSettings() on hover starts the network request. The bundler caches the result of import('./Settings'), so a second call returns the same module and does not download it again. When lazy later runs the same function, it gets the already loaded module.
Handle onFocus as well as onMouseEnter. Keyboard and touch users never hover, and focus gives them the same head start.
The sequence below shows the timing.
Preloading is only a head start
Preloading does not change what Suspense does. If the user clicks before the chunk arrives, React still shows the fallback until the promise resolves. Preloading shortens that wait or removes it. It never makes rendering synchronous.
The preload call also returns a promise. If the download fails, calling loadSettings() from an event handler produces an unhandled promise rejection. The later render calls the import again, and a failure there reaches your error boundary. If you want quieter logs, attach a catch to the preload call:
const preloadSettings = () => {
loadSettings().catch(() => {
// Ignore. The real render will retry and report the error.
});
};Other preload triggers
Hover and focus are the cheapest triggers. Two more are common.
- After the first screen is ready. Preload likely next pages once the current page has rendered and the browser is idle.
- On a related action. Preload an editor when the user opens a document list, since an edit is the likely next step.
Here is the idle approach:
import { lazy, useEffect } from 'react';
const loadReports = () => import('./Reports');
const Reports = lazy(loadReports);
export function useIdlePreload(load) {
useEffect(() => {
const run = () => load().catch(() => {});
if ('requestIdleCallback' in window) {
const id = requestIdleCallback(run);
return () => cancelIdleCallback(id);
}
const id = setTimeout(run, 2000);
return () => clearTimeout(id);
}, [load]);
}Call useIdlePreload(loadReports) in a component that is already on screen. The effect schedules the import when the browser has spare time, so the preload does not compete with work the user is waiting for.
Trade-offs
Preloading spends bandwidth on code the user might never use. Use it where the odds are high.
| Trigger | Accuracy | Cost if wrong | Lead time |
|---|---|---|---|
| Hover or focus | High | Low | Short, often 100 to 300 ms |
| Idle after load | Medium | Medium | Long |
| Related action | Medium to high | Medium | Medium |
Avoid preloading everything at startup. That brings back the large initial download that code splitting was meant to remove.
On slow or metered connections, consider skipping idle preloads. The navigator.connection.saveData flag, where the browser supports it, tells you the user asked to save data.
Common mistakes
- Defining the import function inside a component. Each render creates a new function.
lazyshould be called at module level, and the loader should be a stable reference. - Preloading a different path than the lazy import.
import('./Settings')andimport('./settings')can resolve to different modules. Share one loader variable so both calls use the same specifier. - Assuming preload renders the component. The import only downloads and evaluates the module. Nothing mounts.
Exercise
A user clicks a link before its preloaded chunk has finished downloading. What do they see, and why?
Show answer
They see the Suspense fallback. Preloading only starts the download early. The lazy component still suspends until the import promise resolves, and then it renders from the cached module.
Exercise
Why should loadSettings be defined once at module level and passed to both lazy and the hover handler?
Show answer
A single stable loader means both calls use the same import specifier, so the bundler returns the same cached module. It also avoids creating a new function on each render.