React lazy loading - when to use

橙三吉。 提交于 2020-12-04 03:10:56

问题


I have a pretty large app, which by now has a bundle size of around 2mb combined (3 chunks or so). In order to improve loading times, I decided to start using the relatively new React Lazy.

Here's an example of a lazy import:

const Wizard = React.lazy(() => import('./components/wizards/Wizard'));

I understand the general idea, but I still struggle to understand what's the downside, other than having to wait a bit to load a chunk from time to time.

According to what I read, I have no reason to use a regular import.

My question is: should I just use lazy import on every component import in my app? Why? Why not?

I'd love to hear what you guys think.


回答1:


No, for every component it no needed. It make sense to use for each layout or page. A good place to start is with routes. Most people on the web are used to page transitions taking some amount of time to load. You also tend to be re-rendering the entire page at once so your users are unlikely to be interacting with other elements on the page at the same time.

For example, you creating application for news aggregator. Your application include two pages such as NewsList and NewsItemPage. Every pages includes several different components. In this example make sense to use lazy loading component for each other page. And then it will load the components it needs.

The application also has a Header and Footer. They should be loaded in the usual way. Since they are used on every page, and there is no point in asynchronous loading.

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import React, { Suspense, lazy } from 'react';

import Header from './components/Header';
import Footer from './components/Footer';

const NewsList = lazy(() => import('./pages/NewsList'));
const NewsItemPage = lazy(() => import('./pages/NewsItemPage'));

const App = () => (
  <Router>
    <Header />
      <Suspense fallback={<div>Loading...</div>}>
        <Switch>
          <Route exact path="/" component={NewsList}/>
          <Route path="/news/:id" component={NewsItemPage}/>
        </Switch>
      </Suspense>
    <Footer />
  </Router>
);



回答2:


I have not started using it just yet. But I think the most optimistic approach would be to do a regular import on all components which are required on the landing page. Everything else such as any other route than home should use lazy loading. That is the general idea I guess.



来源:https://stackoverflow.com/questions/60390144/react-lazy-loading-when-to-use

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