Strongly Typed Lazy Loading
Here we have a LazyLoad
component, inspired by a real component found in the Sentry codebase.
function Lazyload({ loader, ...props }: Props) {
const LazyComponent = useMemo(() => lazy(loader), [loader]);
return (
<Suspense fallback={"Loading..."}>
<LazyComponent {...props} />
Transcript
00:00 In this exercise, we're going to look at a component that does some sort of interesting function. It's a lazy load component. What that does is it takes in a loader, which allows it to import a sort of component from the outside,
00:14 and then basically stick that in a use memo, load it with react.lazy, and then go and render that component with a suspense boundary wrapping it. What this means is you get to kind of have your cake and eat it too. You don't need to declare a separate component outside this.
00:30 You can just inline lazy load this component. I actually saw this in the Sentry code base, and it really kind of inspired me to make this exercise. The idea of this is that the component that we have here is a fake external component. Let's go have a look at it. It takes in a props.id and then sort of returns div hello.
00:49 And what we're trying to do here is we then, based on what's loaded here, we then type the props that this receives. So this should receive id of 123, and this should error because id is missing, and this one should error because number is not assignable to type string. We're passing in a number, and id should be a string. So you'll need a few things.
01:09 You'll need to make sure that it's a generic component. You'll need to make sure that you use react.component props, as well as react.component type, which we've seen before. And I'll link to the previous exercise where we covered react.component type. And also, you might just want to take a look at the type definition for lazy, just to kind of understand what's going on there.