Created
March 21, 2024 19:14
-
-
Save marcandrewb/b1e1ffd618ea7f96da938aa3536445a3 to your computer and use it in GitHub Desktop.
Lazy Load
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
import { ComponentProps, ComponentType, lazy, Suspense, useMemo } from "react"; | |
type Props<C extends ComponentType<any>> = { | |
loader: () => Promise<{ | |
default: C; | |
}>; | |
} & ComponentProps<C>; | |
function LazyLoad<C extends ComponentType<any>>({ | |
loader, | |
...props | |
}: Props<C>) { | |
const LazyComponent = useMemo(() => lazy(loader), [loader]); | |
return ( | |
<Suspense fallback={"Loading..."}> | |
<LazyComponent {...props} /> | |
</Suspense> | |
); | |
} | |
<> | |
<LazyLoad loader={() => import("fake-external-component")} id="123" /> | |
<LazyLoad | |
loader={() => import("fake-external-component")} | |
// @ts-expect-error number is not assignable to string | |
id={123} | |
/> | |
{/* @ts-expect-error id is missing! */} | |
<LazyLoad loader={() => import("fake-external-component")} /> | |
</>; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment