Skip to content

Instantly share code, notes, and snippets.

@marcandrewb
Created March 21, 2024 19:14
Show Gist options
  • Save marcandrewb/b1e1ffd618ea7f96da938aa3536445a3 to your computer and use it in GitHub Desktop.
Save marcandrewb/b1e1ffd618ea7f96da938aa3536445a3 to your computer and use it in GitHub Desktop.
Lazy Load
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