Lazy Loading with Suspense in React JS

While developing the React applications, we usually use images and videos. We also install third-party packages/libraries, make API calls, and can do various things. It automatically increases the time to load our mobile app development. And it results in a poor user experience. That’s where the lazy loading comes into place. Hence, it lets us lay content before displaying it in the application.

We also avoid the pre-content while it is still out of view, and it will concentrate on whole resources on content in the view. In this guide, we will see how to implement lazy loading and code splitting functionality, which allows us to control code splitting without requiring additional libraries.

What is lazy loading in React?

It typically bundles the entire application at once, loading everything for us, including the entire web app pages, images, content, and much more, which may cause a slow load time and generally poor performance, depending on the size of the content and the available internet bandwidth at the time.

Thanks to lazy loading, specific components can only be loaded when required. Usually, we divide the code into logical parts that can be lazy loaded with the material.

The technique of utilizing carefully monitored experiments to improve a web application’s performance is known as web optimization. Let’s look at a straightforward analogy to grasp better how lazy loading React components contribute to website optimization.

As a result, only a piece of a web page renders when a user accesses it rather than the complete page. The remaining webpage won’t load until the user scrolls to that area, thanks to React lazy loading. If you want to use lazy loading in React development, you can hire React developers who have complete knowledge and will enhance your business app.

Benefits of lazy loading React component

Performance is the main advantage of lazy loading in React making app development faster. Our application will run faster and require less DOM load time if we load less JavaScript code into the browser. Users can access a web page even if the content has not yet been loaded.

1. A quicker start-up time:

To enable a quicker initial page load time, React lazy loading helps lower the page weight.

2. An improved user experience:

An application’s user experience is enhanced by React lazy loading. Effective user experience (UX) aids customer retention and revenue growth.

3. Consuming less bandwidth:

Images that load slowly on demand can save data and bandwidth. Users who don’t have access to fast internet or large data plans will find this to be especially helpful.

4. Less effort required of the browser:

When React lazy loads images, browsers do not need to process the images until users scroll to that page area and request them.

Dynamic imports in React

This can make utilizing your programme extremely difficult and painfully slow. The bundle can be divided into smaller parts via code splitting, and the most crucial chunk can be loaded first, followed by a lazy loading of the other secondary portions.

Using dynamic imports, which use the import() syntax, is one method for dividing code. A module is loaded by calling import(), which relies on JavaScript Promises. Therefore, it returns a promise that is either accepted if the module can be loaded or denied if it cannot.

	
import ('moment’)
.then(({default:moment}})=>{
const tomorrow=moment().startOf('day').add(1,'day);
return tomorrow.format('LLL');
})

Also Read: Top 8 React Boilerplates in 2023

What is React lazy?

With the help of code splitting and the new React lazy function, you may load React components in a lazy fashion without the aid of any additional third-party libraries. A third-party library was formerly required to accomplish this.

The “React lazy()” function is now a part of the core React component library. We can lazy load React components with ease as a result of this.

Rendering React components that are loaded using the dynamic import() technique is simple with “React lazy().” The bundle containing the component only loads when the component is loaded since the components are rendered as ordinary components.

A function that must invoke a dynamic import is sent to React lazy() (). A Promise that resolves to a module with a default export that includes a React component must be returned by this dynamic import.

	
import OtherComponent from './OtherComponent';

What is the Difference Between Dynamic Import and Regular Import?

What distinguishes a dynamic import() from a standard import()? Between these two imports, the dynamic import is the primary distinction ()
let OtherComponent = undefined;

	
if (false) {
  OtherComponent = React.lazy(() => import('./OtherComponent.js'));
}

When calling the component on regular import(), you import the component:

	
import AB from './AB.js';
 
function App() {
  return <AB/>
}



import A from './A.jsx';
import B from './B.jsx';

function AB() {
  return <A/>; 
}

Also Read: Understanding React Native New Architecture in 2023

What is React Suspense?

A React component called React Suspense allows components to “wait” for something before rendering. React Suspense only supports dynamically loading components using React Lazy, which is one use case (). It will later support other use cases like data fetching.

Only when a component constructed with React lazy() is rendered is it loaded, as a result, while the lazy component is loading, you must provide some placeholder content. For example, a loading indication would let users know something is loading while waiting.

While we wait for the lazy component to load, we can display a loading indication using the React Suspense component.

	
import React, { Suspense } from 'React';
 
const OtherComponent = React.lazy(() => import('./OtherComponent'));
 
function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

What may be used to wrap component imports so that they can be loaded slowly?

Even more, than one lazy component can be wrapped in a single React Suspense component.

import React, { Suspense } from 'react';

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

 

Also Read: How to Scroll to a List Item in React?

Avoiding Fallback in React Suspense

We’ve seen how React Suspense can enhance user interaction while lazy loading a component in React with the component supplied to the fallback props. What happens, though, if the component used as a fallback is degrading the user’s experience?

Let’s look at a code example to see what happens when we utilize the React Suspense component without giving a fallback prop. This already defeats one of the purposes of lazily loading a React component by producing a poor user experience.

	
import React, { Suspense } from 'React';
 
const OtherComponent = React.lazy(() => import('./OtherComponent'));
 
function MyComponent() {
  return (
    <div>
      <Suspense>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

Why do we keep getting errors? If not by deleting the fallback prop from the Suspense component, how else are we supposed to prevent the component from being sent to the fallback prop?

Using Suspense

Loader.js

	
const style = {
  height: "100vh",
  display: "flex",
  justifyContent: "center",
  alignItems: "center",
}
 
const Loader = () => {
  return (
    <div style={style}>
        <h1>Loading...</h1>
    </div>
  )
}
 
export default Loader;

MyComponent.js

import React, { Suspense } from 'react';
import Tabs from './Tabs';
import Loader from './Loader';

const Comments = React.lazy(() => import('./Comments'));
const Photos = React.lazy(() => import('./Photos'));
 
function MyComponent() {
  const [tab, setTab] = React.useState('photos');
   
  function handleTabSelect(tab) {
    setTab(tab);
  };
 
  return (
    <div>
      <Tabs onTabSelect={handleTabSelect} />
      <Suspense fallback={<Loader />}>
        {tab === 'photos' ? <Photos /> : <Comments />}
      </Suspense>
    </div>
  );
}

 

Comments will be suspended when users move the tab from “pictures” to “comments” in the code example above. Until Comments have fully loaded, the user will then see a loader. Given that the Comments component isn’t yet prepared to render anything, this makes reasonable. React is forced to display the Loader above in order to maintain consistency in the user experience.

	
function handleTabSelect(tab) {
  startTransition(() => {
    setTab(tab);
  });
}

You are informing React that changing the tab to “comments” is a transition that might take some time rather than an urgent upgrade.

Also Read: Integrating Google maps with React Applications

Error Handling for React Lazy

As was already explained, while using React lazy, the import() function produces a promise (). Several factors, including network failure, file not found issues, file path errors, and others, can cause this promise to be refused.

	
import React, { Suspense } from "React";
 
const LazyComponent1 = React.lazy(() => import("./OtherComponent1"));
const LazyComponent2 = React.lazy(() => import("./OtherComponent2"));
const LazyComponent3 = React.lazy(() => import("./OtherComponent3"));
import ErrorBoundary from "./error.boundary.js";
 
const MyComponent = () => (
    <div>
        <ErrorBoundary>
            <Suspense fallback={<div>Loading...</div>}>
                <LazyComponent1 />
                <LazyComponent2 />
                <LazyComponent3 />
            </Suspense>
        </ErrorBoundary>
    </div>
);

Error Boundaries can manage recovery, handle errors, and present a pleasant user experience. As demonstrated in the code example above, Error Boundaries can be used anywhere above a lazy component to display an error state when there is a network error, a file not found, a defect, or a file path issue.

Route-based lazy loading in React

You may accomplish route-based code-splitting without relying on an external package using React. lazy() and React.Suspense. Your app’s route components can easily be changed to lazy components, and then you may wrap each route with a suspense component.

	
import React, { Suspense } from 'React';
import { Router } from '@reach/router';
import Loading from './Loading';

const Home = React.lazy(() => import('./Home'));
const Dashboard = React.lazy(() => import('./Dashboard'));
const Overview = React.lazy(() => import('./Overview'));
const History = React.lazy(() => import('./History'));
const NotFound = React.lazy(() => import('./NotFound'));

function App() {
  return (
    <div>
      <Suspense fallback={<Loading />}>
        <Router>
          <Home path="/" />
          <Dashboard path="dashboard">
            <Overview path="/" />
            <History path="/history" />
          </Dashboard>
          <NotFound default />
        </Router>
      </Suspense>
    </div>
  )
}

Schedule an interview with React developers

Conclusion

Using lazy loading is a wonderful technique to improve page performance and keep visitors on your site. It might assist you in developing effective and user-friendly solutions if used properly.

Code splitting and lazy loading React components have never been easier, thanks to React. lazy() and React.Suspense. With these features, boosting your React app’s performance and enhancing the user experience is simpler than ever.

Hence, with lazy loading and suspense, React developers can quickly create and deliver a high-quality mobile app that retains the users’ attention. However, if you face any issues while integrating this function, you can take the help of a mobile app development company with an expert team who will happily aid you. The team will also try their best to give the desired outcomes to their valuable clients. Get in touch with us for more details!

 

Frequently Asked Questions (FAQs)

 

1. What is suspense in lazy loading?

Suspense is a component required by a lazy function that is usually used to wrap the lazy components. The multiple lazy components are wrapped with a suspense component. Hence, it takes the fallback property, which accepts a React element you want to render as lazy components are being loaded.

2. Does React lazy enhance performance?

React. Lazy () is a vital tool for optimizing the performance of React apps. It allows the engineers to import the components dynamically, reducing the initial bundle’s size and improving the app’s performance.

3. What is the difference between React suspense and lazy loading?

The React. lazy function allows you to import the dependencies dynamically and renders the dependency s component in only one line of code. However, the lazy components are rendered inside the suspense component, which aids you in reflecting the fallback content while the lazy component loads.


Book your appointment now

Get in touch





    Stay up-to-date with our blogs