Created
October 23, 2024 13:38
-
-
Save lil5/4f0c9ef2a4ac9817863a49e7054649e7 to your computer and use it in GitHub Desktop.
Lazy with Preload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* eslint-disable @typescript-eslint/no-explicit-any */ | |
import { ComponentType, lazy } from "react"; | |
/** | |
* Returns both the component render function and a prefetch function | |
* | |
* Example: | |
* | |
* ```ts | |
* import { lazyWithPreload } from "~/utils/lazy_with_preload"; | |
* const LargeComponent = lazyWithPreload(()=>import("./LargeComponent")); | |
* const Page = ()=> { | |
* const [showLargeComponent, setShowLargeComponent] = useState(false) | |
* const onHoverBtn = () => LazyComponent.preload() | |
* return ( | |
* <div> | |
* <button onClick={openLargeComponent} onMouseOver={onHoverBtn}>Open</button> | |
* { showLargeComponent ? <LargeComponent.render/> : null} | |
* </div> | |
* ) | |
* } | |
* ``` | |
*/ | |
export function lazyWithPreload<C extends ComponentType<any>>( | |
factory: () => Promise<{ default: C }> | |
) { | |
const Component = lazy(factory); | |
return { render: Component, preload: factory }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment