Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you deconstruct lazily loaded React components?

Using es6 imports, you can do this:

import { MyComponent } from "../path/to/components.js";

export default function () {
  return <MyComponent/>;
}

Can I do it with React.lazy too?

const { MyComponent } = lazy(() => import("../path/to/components.js"));

I get the following error, but I'm not sure if it's related to this or some other bug I have:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

like image 272
Paul Razvan Berg Avatar asked Nov 10 '19 18:11

Paul Razvan Berg


People also ask

What are the benefits of lazy loading React components?

Benefits of Lazy loading React componentsLoad the minimal code to the browser that will render a page. Load additional small chunks of code when needed. By loading less JavaScript code to the browser, that will default to better performance and better TTI results.

What does React lazy return?

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.

Does React router lazy load?

Lazy Loading on route level with React Router is a powerful feature. Usually a client-side rendered React applications comes as one bundle from a web server. However, when enabling lazy loading, the bundle is split into smaller bundles.


3 Answers

Here is how I did it when I faced this problem with FontAwesome:

const FontAwesomeIcon = React.lazy(()=> import('@fortawesome/react-fontawesome').then(module=>({default:module.FontAwesomeIcon})))
like image 166
gxmad Avatar answered Oct 16 '22 09:10

gxmad


You can if you use react-lazily.

import { lazily } from 'react-lazily';
const { MyComponent } = lazily(() => import("../path/to/components.js"));

It also allows importing more than one component:

const { MyComponent, MyOtherComponent, SomeOtherComponent } = lazily(
  () => import("../path/to/components.js")
);

See this answer for more options.

like image 11
JLarky Avatar answered Oct 16 '22 10:10

JLarky


React.lazy currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default. This ensures that tree shaking keeps working and that you don’t pull in unused components.

// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;
// MyComponent.js
export { MyComponent as default } from "./ManyComponents.js";
// MyApp.js
import React, { lazy } from 'react';
const MyComponent = lazy(() => import("./MyComponent.js"));

More info: https://reactjs.org/docs/code-splitting.html#named-exports

like image 3
Ahmed Elazazy Avatar answered Oct 16 '22 09:10

Ahmed Elazazy