React.lazy and prefetching components

若如初见. 提交于 2020-12-04 09:04:45

问题


I have a 2 step Application Flow that looks like this:

const Step1 = React.lazy(() => import('./Step1'));
const Step1 = React.lazy(() => import('./Step2'));

<Suspense fallback={<Loading />}>
  <Route path="/step1" render={() => <Step1 />} />
  <Route path="/step2" render={() => <Step2 />} />
</Suspense>

Using React.lazy, I can defer loading <Step2 /> while the user is on <Step1 />, which can improve initial page load. However, I would like to prefetch <Step2 /> while the user is on <Step1 /> as an optimization. Is there an API to do this with React.lazy?

Edit:

To elaborate - I'm using a router to render a 2 step form. Initially the user will start on /step1. After the user completes all the tasks in <Step1 /> they will be routed to path /step2. At this point the router will render the <Step2 /> component.

I'm asking if there is a pattern to pre-fetch <Step2 /> while the user is still on <Step1 />.


回答1:


I was also reading about this few days back and I liked this approach:

Enhance the React.lazy to have a callback that can be used to load the component. Something like this:

function lazyWithPreload(factory) {
  const Component = React.lazy(factory);
  Component.preload = factory;
  return Component;
}

const ComponentToPreload = lazyWithPreload(() => import("./Component"));

/* usage in Component */

ComponentToPreload.preload(); // this will trigger network request to load the component


In this way, you can preload the component wherever you want. Like on click event or after the current component has Mounted.

Must read the original post: https://medium.com/hackernoon/lazy-loading-and-preloading-components-in-react-16-6-804de091c82d


If you are using react-loadable. You can check this: https://github.com/jamiebuilds/react-loadable#preloading

Hope this helps!



来源:https://stackoverflow.com/questions/58687397/react-lazy-and-prefetching-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!