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;
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:
- MyErrorBoundary handles loading errors
- Suspense gives loading progress feedback
- 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?