DEV Community

Lem
Lem

Posted on

React's `lazy` with Typescript and named exports

The lazy function in React is a great way to keep your component tree pruned. An example is when your screen has modals that you show/hide depending on some conditions - maybe that modal is invisible until you need it - the user doesn't see it, but it still exists in your component tree, and if that modal is heavy, all of those its components are loaded into memory even if the user can't see any of them.

Example:

<Modal
  isVisible={opened}
  onModalHide={onCancelPressed}
>
  {children}
</Modal>
Enter fullscreen mode Exit fullscreen mode

What you can do is to lazily load Modal when you need to show it:

const Modal = lazy(() => 
  import("../path/to/Modal")
);
Enter fullscreen mode Exit fullscreen mode

However, you'll have to make sure that Modal is a default export. If it isn't a default export, your IDE will alert you to this error:

TS2322 Property 'default' is missing in type 'typeof import("path/to/Modal")' but required in type '{ default: ComponentType; }'.

Default exports might not be what you want. Sometimes default exports make searchability difficult, and your team might prefer named exports. In that case, you can do this:

const Modal = lazy(() => 
  import("../path/to/Modal")
  .then((module) => ({default: module.Modal})),
);
Enter fullscreen mode Exit fullscreen mode

This then allows you not only to render the modal but also to only load it when needed:

{ opened ? <Modal /> : null}
Enter fullscreen mode Exit fullscreen mode

(Inspired by a YT Short by Cosden Solutions)

Top comments (0)