Part 13 / Topic 4 of 5
Code-splitting with React.lazy and Suspense
Most sessions on an IRCTC-style account page never open the settings panel. There is no reason to make every visitor download its code before they have asked for anything. examples/04_lazy_settings_panel.jsx is an entirely ordinary component, kept in its own file for one reason: import() splits at file boundaries, so whatever should live in its own chunk needs a file a dynamic import can point at. examples/05_lazy_and_suspense_settings_panel.jsx is what actually loads it:
// examples/05_lazy_and_suspense_settings_panel.jsx
const SettingsPanel = lazy(() => import("./04_lazy_settings_panel.jsx"));
export function SettingsPanelLauncher({ userName }) {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen((isOpen) => !isOpen)}>{open ? "Close settings" : "Open settings"}</button>
{open && (
<Suspense fallback={<p>Loading settings...</p>}>
<SettingsPanel userName={userName} />
</Suspense>
)}
</div>
);
}
React.lazy takes a function that returns a dynamic import - not the import's result - because React needs to be able to call it again on a later attempt if the first one fails (Exercise 6 builds exactly that case, a failed lazy load caught by a wrapping boundary). Suspense's fallback is what covers the gap between "asked for" and "arrived": clicking "Open settings" really shows "Loading settings..." first, and only then the real panel, found with findByText rather than a synchronous query because the load is genuinely asynchronous even when it resolves almost immediately (examples/05_lazy_and_suspense_settings_panel.test.jsx).
Done here? The practice set for Part 13 — including the solutions — is on the part page.