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.

Revisions

  1. marcandrewb created this gist Mar 21, 2024.
    33 changes: 33 additions & 0 deletions lazy.tsx
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    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")} />
    </>;