import { createElement, lazy, type ComponentType } from "react"; // A route-level lazy component whose code can be fetched BEFORE its first render. // // React.lazy alone suspends on every first render, even when the chunk is already in the browser: the // module promise settles a tick later, so the Suspense fallback is committed and painted for a frame or // several. On a module switch that is a "Loading…" flash in place of the page, on every first visit. // Here, once `preload()` has resolved, the component renders the loaded module synchronously and never // suspends at all. // // Choosing per render (`loaded ?? Lazy`) cannot swap a mounted page's component type and remount it: // a render that suspends on `Lazy` is never committed (React discards a suspended new mount), and // `loaded` is set before `Lazy`'s own promise resolves — so every committed render of a mount sees the // loaded module. Measured, not assumed: the state test in lazyWithPreload.dom.test.tsx stayed green // with a per-mount pin removed, in a boundary that was already showing content. export type PreloadableComponent

= ComponentType

& { /** Fetch the component's code now. Idempotent; a failed fetch is retried by the next call. */ preload: () => Promise; }; export function lazyWithPreload

( factory: () => Promise<{ default: ComponentType

}>, ): PreloadableComponent

{ let loaded: ComponentType

| null = null; let pending: Promise | null = null; const preload = () => (pending ??= factory().then( (m) => { loaded = m.default; }, (err: unknown) => { pending = null; throw err; }, )); const Lazy = lazy(() => preload().then(() => ({ default: loaded as ComponentType

}))); function Preloadable(props: P) { return createElement(loaded ?? (Lazy as unknown as ComponentType

), props); } return Object.assign(Preloadable, { preload }); }