React preloading components with Lazy + Suspense React preloading components with Lazy + Suspense reactjs reactjs

React preloading components with Lazy + Suspense


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.

React.lazy(() => Promise<{default: MyComponent}>)

So if you want to preload, all you have to do is execute the promise yourself ahead of time.

// So change this, which will NOT preloadimport React from 'react';const MyLazyComp = React.lazy(() => import('./path/to/component'));/*********************************************/// To this, which WILL preloadimport React from 'react';// kicks off immediately when the current file is importedconst componentPromise = import('./path/to/component');// by the time this gets rendered, your component is probably already loaded// Suspense still works exactly the same with this.const MyLazyComp = React.lazy(() => componentPromise);

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}.

import React from 'react';const MyLazyComp = React.lazy(() => importMapsComponent('./path/to/comp'));


Not sure how much help this will be, but here is a code sandbox that works (Demo gets loaded by componentDidMount). It is a considerably simplified version of your code using create-react-app for the config. Perhaps you can take this as a starting point and morph it gradually closer to your app to see what causes the dynamic import to no longer work as desired.