iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📘

How to Cleanly Lazy Import Named Exports in React

に公開
2025/07/23
1件

React.lazy is used for lazy loading React components.

import { lazy, Suspense, useState } from 'react';

const MarkdownPreview = lazy(() => import("./MarkdownPreview"));

export default function App() {
  const [show, setShow] = useState(false);
  return (
    <div>
      <button onClick={() => setShow(true)}>show</button>
      <Suspense>
        {show && <MarkdownPreview />}
      </Suspense>
    </div>
  );
}

https://react.dev/reference/react/lazy

It handles the asynchronous import function internally and makes it possible to lazy load components.
It's similar to React.use.
You can improve performance by delaying the loading of components until they are actually needed, such as when you have dependencies that aren't necessary for the initial render due to conditional branching like if statements.
This lazy function expects a default export, so it cannot be used directly for named exported components and requires a bit of ingenuity.

How to Handle Individually

It is possible to resolve imports individually by writing the following boilerplate using .then for immediate resolution.

import { lazy } from "react";

const SomeComponent = lazy(() => import("./foo").then((module) => ({ default: module.SomeComponent })));

What this does is simply select the desired export from the imported module and convert it into a default export.
However, writing this every time is tedious.

How to Create a Utility Function for Reuse

https://qiita.com/KokiSakano/items/b6d4e6875443064032b4

This is the method introduced in the article above.
By creating a utility function, you can delegate the handling of named exports to this function.

import { lazy, type ComponentType } from "react";

export const lazyImport = <T extends { [P in U]: ComponentType<any> }, U extends string>(
  factory: () => Promise<T>,
  name: U,
) => ({
  [name]: lazy(() => factory().then((module) => ({ default: module[name] }))),
});
Usage Example
const { SomeComponent } = lazyImport(() => import("./foo"), "SomeComponent");

It is a bit concerning that you have to specify the name on the right side even though it is already specified on the left.
Since it does not accept an array, it seems you cannot import multiple components from the same module at once.

Using react-lazily

Looking for a better way, I found the following library.
If you are allowed to install libraries, you can import named exports cleanly using react-lazily.

https://www.npmjs.com/package/react-lazily

Although it is a library, it is lightweight at 268 bytes for a single function, so there is little guilt in increasing dependencies.

import { lazily } from "react-lazily";

const { SomeComponent } = lazily(() => import("./foo"))

Named exported components can be used with the same feel as regular React.lazy.

Diagram showing multiple components being imported from a single import while maintaining type completion

In this way, you can lazy import multiple components from a single import while maintaining type completion.
I also like that the type definition does not become LazyExoticComponent.
Since JSDoc comments are not lost, the comments you wrote remain available when specifying Props.

It may be obvious when you think about it, but please note that if you use multiple components imported from the same module in different Suspense boundaries, both will Suspend.
It is fine if they are within the same Suspense.
I did a rough verification in the repository below just in case.
Checking the network tab confirms that the source containing both components is loaded simultaneously.
Also, when one component is loaded, both are Suspended.

https://bmthd.github.io/lazy-import/
Source Code

When I looked at the implementation, it was using Proxy and type casting with as.

https://github.com/JLarky/react-lazily/blob/main/src/core/lazily.ts

I wouldn't have thought of that...!

I don't use it myself, but there seems to be a library called @loadable/component for SSR in server frameworks, and it appears there is an API that can be used in conjunction with it.

Conclusion

I have introduced a way to cleanly lazy import named exports when using React.lazy.
react-lazily is lightweight and easy to use, so please give it a try when you use lazy imports.

GitHubで編集を提案

Discussion

glassonion1glassonion1

ライブラリの遅延読み込みで悩んでたのでめちゃくちゃ参考になりました。ありがとうございます!

1