How to optimize your React Application using Lazy Loading....

How to optimize your React Application using Lazy Loading....

when building a large scale React Application a lot of thought process needs to be taken care of before launching the app. The biggest and greatest challenge I would say would be "separation of concern". We use modular programming approach to separate our components say Login page, Signup Page, Header, CTA, etc which is indeed a good practise but things get complicated when we initiate the build process. After building whole of our React code get's minified to few or a single js file.

This minified compressed js file will load all of your react components once you run your react app. This process of compressing and minifying of React app is called bundling which is done by bundlers like Webpack, vite and parcel. It works absolutely fine for smaller apps with few amounts of components but for a large scale app like netflix, makemytrip , Airbnb, etc the app needs to be breakdown into smaller chunks so that whenever a user visits a particular type of services then that piece of chunk should handle the business operation.The issue with the minified js file is it tries to run all the code at once which might not give the better UX, your app may feel laggy or bogged down, so to fixed this we can use Lazy Loading to improve the UX.

Lazy loading is also known as code splitting, chunking, Dynamic Bundling, etc., allows us to load components asynchronously, which can enhance the initial loading time of our application by deferring the loading of non-essential components until they are needed.

Before moving on to use lazy loading, we need to address a few questions.

How and when to make smaller bundles?

Smaller bundles can be created by strategically splitting the code based on user interactions, application routes, or logical divisions within the application. For instance, separate bundles can be generated for different pages, features, or modules of the application. By analyzing user behavior and application usage patterns, we can identify areas where lazy loading can be implemented effectively. A logical division would ensure that the bundle should have enough code for a feature to work independently.

Let's see how Lazy Loading works with an example.

The general syntax that let's you to defer loading component until its rendered for the first time would be like : const SomeComponent = lazy(load).

import React, { Suspense, lazy } from 'react';

const BigComponent = lazy(() => import('./BigComponent'));

function App() {
  return (
    <div>
      <h1>My App</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyLoadedComponent />
      </Suspense>
    </div>
  );
}

// This is a regular component that uses lazy loading
function LazyLoadedComponent() {
  return (
    <div>
      <h2>This component is lazily loaded</h2>
      <BigComponent />
    </div>
  );
}

export default App;

In the below code block the import statement is not the traditional one which we use for importing components or static files . Here the import method takes an argument which is the path of the component for which we want to implement the lazy loading. This code relies on dynamic import(), which might require support from your bundler or framework. Using this pattern requires that the lazy component you’re importing was exported as the default export.

const BigComponent = lazy(() => import('./BigComponent'));

Here Suspense Component with fallback act as a wrapper wrapping the content with an intermediate content which is rendered while the actual wrapped content is being loaded. The content inside fallback acts as a shimmer UI that's being displayed for time being untill the actual content is ready to render.

<Suspense fallback={<div>Loading...</div>}>
        <LazyLoadedComponent />
</Suspense>

Note:- The fallback prop of Suspense is required. It defines the UI that will be displayed while the component is being loaded.

Thus, by using Lazy loading we can build scalable React apps. Also for better visual representation of our app we can use Shimmer UI but that's for later part.