Skip to content

Instantly share code, notes, and snippets.

@lil5
Created October 23, 2024 13:38
Show Gist options
  • Save lil5/4f0c9ef2a4ac9817863a49e7054649e7 to your computer and use it in GitHub Desktop.
Save lil5/4f0c9ef2a4ac9817863a49e7054649e7 to your computer and use it in GitHub Desktop.
Lazy with Preload
/* 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