When should you use React's lazy loading feature?
P粉976737101
P粉976737101 2023-08-24 23:11:02
0
2
497
<p>I have a fairly large application and the bundle size is now about 2MB (about 3 chunks). To improve load times, I decided to start using the relatively new React Lazy. </p> <p>This is an example of lazy loading: </p> <pre class="brush:php;toolbar:false;">const Wizard = React.lazy(() => import('./components/wizards/Wizard'));</pre> <p>I understand the general idea of ​​the concept, but I'm still having a hard time understanding what the downside is other than occasionally having to wait a while for chunks to load. </p> <p>Based on what I've read, I have no reason to use regular imports. </p> <p><strong>My question is: Should I use lazy loading on every component import in my application? Why? why not? </strong></p> <p>I'd love to hear your thoughts. </p>
P粉976737101
P粉976737101

reply all(2)
P粉790819727

I haven't started using it yet. But I think the most optimistic approach is to do regular imports of all the components you need on the homepage. Any other routes that are not the homepage should use lazy loading. This is the general train of thought I have.

P粉481035232

No, not required for every component. It only makes sense to use it in every layout or page. A good place to start is routing. Most people on the web are used to page transitions taking a certain amount of time to load. You also tend to re-render the entire page at once, so your users are less likely to interact with other elements on the page at the same time.

For example, you are creating a news aggregation application. Your application consists of two pages such as NewsList and NewsItemPage. Each page contains several different components. In this example, it makes sense to use lazy loading components for every other page. It will then load the components it needs.

The application also has a Header and Footer. They should be loaded in the usual way. Because they are used on every page and loading asynchronously doesn't make sense.

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>
);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template