The simplest way to use dynamic imports for React components in 2021?

I recently tried to add dynamic imports to the react-router of a Meteor application that I just upgraded from 1.10.2 to 2.0. Knowing nothing about dynamic imports beforehand I tried to search this forum and github issues for a solution. Most solutions recommend a dependency on react-loader or react-loadable. I also found the more recent @loadable/component through the web. However! There is a super simple way to have dynamically loaded components using the modern React feature Suspense. Suspense does not yet allow to do all that was promised when it was first revealed, but it can achieve the following:

import {Suspense, lazy} from 'react';

import MyErrorBoundary from './MyErrorBoundary.jsx';
import MyLoading from './MyLoading.jsx';
const MyComponent = lazy(() => import('./MyComponent.jsx'));

const App = () => (
	<MyErrorBoundary>
		<Suspense fallback={<MyLoading />}>
			...
			<MyComponent />
			...
		</Suspense>
	</MyErrorBoundary>
);

export default App;

:warning: MyComponent needs to be the default export of MyComponent.jsx (otherwise you get this error).

In my opinion, one important trait of this approach is the decoupling of three aspects of the dynamic import it offers in a declarative way:

  1. MyErrorBoundary handles loading errors
  2. Suspense gives loading progress feedback
  3. MyComponent actually renders the component

My understanding is that other solutions do not provide this decoupling. At first glance both react-loader and react-loadable seem quite old. Last release of react-loadable was two years ago but it has a much larger userbase than react-loader whose last release was one year ago. I would not use react-loader as it includes a hard dependency on a spinner component. The more recent @loadable/component which is mentioned in React docs as an alternative boasts SSR which Suspense does not provide yet.

How do you approach lazy loading of components today?

1 Like

There is no way to implement ssr using lazy, so now I am also looking for a way to support both ssr and code splitting. I have tried everything you said @loadable/component. There is no way to use it in meteor. You need to configure webpack. Do you know how to use it? This package is updated quickly. He is also the author of react-loadable. Two years ago, he gave up react-loadable and announced the redevelopment of @loadable/component. At the same time.react-loadable has a babel configuration method, so it can be used in meteor

{
  "plugins": [
    "react-loadable/babel"
  ]
}

but the ssr of @loadable/component needs to configure webpack, It is not as simple as react-loadable, so I don’t know how to use it in meteor