Home  >  Q&A  >  body text

When should you use React’s lazy loading feature?

<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粉976737101P粉976737101443 days ago486

reply all(2)I'll reply

  • P粉790819727

    P粉7908197272023-08-25 19:12:59

    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.

    reply
    0
  • P粉481035232

    P粉4810352322023-08-25 14:42:07

    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>
    );

    reply
    0
  • Cancelreply