DEV Community

Cover image for 🦥 React.lazy without a default export
Andrei Luca
Andrei Luca

Posted on • Updated on

🦥 React.lazy without a default export

React v16.6.0 introduced React.lazy that allows to code split without any external libraries.

https://reactjs.org/blog/2018/10/23/react-v-16-6.html

The React.lazy function lets you render a dynamic import as a regular component.

Before:

import OtherComponent from './OtherComponent';

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  );
}

After:

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <OtherComponent />
    </div>
  );
}

https://reactjs.org/docs/code-splitting.html#reactlazy

Althought bellow there is a message

React.lazy takes a function that must call a dynamic import(). This must return a Promise which resolves to a module with a default export containing a React component.

Which means that your OtherComponent should be exported this way

export default function OtherComponent() {
  return (
    <div>OtherComponent</div>
  );
}
Enter fullscreen mode Exit fullscreen mode

But what if you have it exported not as default?

export function OtherComponent() {
  return (
    <div>OtherComponent</div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this case you have to change a bit the import() code when importing this component

const OtherComponent = React.lazy(
  () => import('./OtherComponent').then(module => ({ default: module.OtherComponent }))
);
Enter fullscreen mode Exit fullscreen mode

What are we doing here, is just chaining the Promise returned by import() and adding that default export.

Please keep in mind that component imported with React.lazy should be rendered inside a React.Suspense

https://reactjs.org/docs/code-splitting.html#suspense

Cover Photo by Scott Kelley on Unsplash

Latest comments (4)

Collapse
 
balines_f053b1282 profile image
Carlos Alvidrez

Thank you!

Collapse
 
gollyjer profile image
Jeremy Gollehon

Does this have an affect on tree-shaking?

Collapse
 
iamandrewluca profile image
Andrei Luca

Yes. Dynamic import cannot be analyzed at build time.
You will have to follow React Docs and reexport only wanted component to have dynamic import with tree shaking
reactjs.org/docs/code-splitting.ht...

Collapse
 
gollyjer profile image
Jeremy Gollehon

Excellent. Thanks for the link.