DEV Community

Lem Dulfo
Lem Dulfo

Posted on

2

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)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay