I'm currently using React 16 with Suspense and Lazy to code-split my codebase. Although I would like to preload components.
In my example below I got two routes. Is there a way to preload Demo
as soon Prime
did mount? I've tried to create another dynamic import in the componentDidMount
of the Prime
page, but React.lazy
doesn't seem to get that that's the same file as the dynamic import below.
import React, { lazy, Suspense } from 'react';
import { Switch, Route, withRouter } from 'react-router-dom';
import GlobalStyle from 'styles';
import Loading from 'common/Loading';
const Prime = lazy(() => import(/* webpackChunkName: "Prime" */'modules/Prime'));
const Demo = lazy(() => import(/* webpackChunkName: "Demo" */'modules/Demo'));
const App = () => (
<main>
<GlobalStyle />
<Suspense fallback={<Loading>Loading...</Loading>}>
<Switch>
<Route path="/" component={Prime} exact />
<Route path="/demo" component={Demo} />
</Switch>
</Suspense>
</main>
);
export default withRouter(App);
So I've tried different approaches, for example with and without webpackChunkName
and different ways of importing the other component in componentDidMount
, as seen below. The first two approaches of importing the file in componentDidMount
resulted in a Webpack error shown at the bottom of the image below. Only the third proceeded, but made the file 2.[hash].js
in the image, only load after the page was visited, and not on componentDidMount
What am I missing here?
Code of modules/Demo.jsx
:
import React from 'react';
import LogoIcon from 'vectors/logo.svg';
import PageLink from 'common/PageLink';
import Anchor from 'common/Anchor';
import CenteredSection from 'common/CenteredSection';
const Demo = () => (
<CenteredSection variant="green">
<LogoIcon />
<PageLink to="/" variant="green">Go to home page</PageLink>
</CenteredSection>
);
export default Demo;
This is incredibly easy to do, I think there is a misunderstanding about what lazy() and Suspense are doing under the hood.
The only expectation that React.lazy() has is that it takes a function that returns a Promise that resolves with a default component.
So if you want to preload, all you have to do is execute the promise yourself ahead of time.
The fact that this is a known signature makes it for useful for all sorts of other situations. For instance, I have a bunch of components that rely on the google maps api being dynamically loaded, I was able to create a function that loads the google maps api and then imports the component. I won't detail the internals of this example since it's a tangent, but the point is I made myself a function that does a bunch of async stuff and then returns a Promise with an object of {default: Component}.