React.lazy supercharged
Aug 21, 2025
This component takes in a loader prop, which allows it to import a component from the outside. Then it sticks that component in a useMemo, loads it with React.lazy, and renders that component with a Suspense boundary wrapping it. The component that we're working with is an imported fake-external-component that takes in a props.id and returns a simple div with "hello" inside. We currently have some errors because the props are not typed correctly
import { lazy, Suspense, useMemo } from "react";
type Props = {
loader: unknown;
};
/**
* 1. This component is supposed to take a loader function that returns a
* component, and render that component when it's loaded.
*
* But it's not typed correctly, and it's not generic enough.
*/
function LazyLoad({ loader, ...props }: Props) {
const LazyComponent = useMemo(() => lazy(loader), [loader]);
return (
<Suspense fallback={"Loading..."}>
<LazyComponent {...props} />
</Suspense>
);
}
LazyLoad is going to receive different props, so we need to make it generic. In this case, the part that needs to be dynamic is the ComponentType that we're passing in.
import { lazy, Suspense } from 'react';
type LazyComponentProps<Component extends React.ComponentType<any>> = {
loader: () => Promise<{ default: Component }>;
} & React.ComponentProps<Component>;
function LazyLoad<C extends React.ComponentType<any>>({
loader,
...props
}: LazyComponentProps<C>) {
const LazyComponent = useMemo(() => lazy(loader), [loader]);
return (
<Suspense fallback={"Loading..."}>
<LazyComponent {...props} />
</Suspense>
);
}