Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React lazy loading - when to use

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.

like image 956
Sagi Rika Avatar asked Feb 25 '20 08:02

Sagi Rika


2 Answers

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>
);
like image 60
an_parubets Avatar answered Oct 07 '22 05:10

an_parubets


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.

like image 41
Singh Avatar answered Oct 07 '22 03:10

Singh