import type { ComponentType } from "react"; import { inspect, PromiseStatus, resolve, type SyncInspectablePromise, } from "./SyncInspectablePromise"; import { useThenable } from "./useThenable"; export function preloadableLazyComponent

( load: () => SyncInspectablePromise<{ default: ComponentType

}>, ): { Component: ComponentType

; preload: () => Promise } { let cachedLoadingPromise: SyncInspectablePromise<{ default: ComponentType

; }> | null = null; const cachedLoad = () => { if (!cachedLoadingPromise) { cachedLoadingPromise = load(); } return cachedLoadingPromise; }; const Component = (props: P) => { const { default: Component } = useThenable(cachedLoad()); return ; }; return { Component, preload: () => { const componentPromise = cachedLoad(); if (inspect(componentPromise).status === PromiseStatus.FULFILLED) { return resolve(undefined); } return componentPromise.then(() => undefined); }, }; }