Page Content

Tutorials

What Are The Lazy Loading in React.js With Code Example

Lazy Loading in React.js

React.js programs use “lazy loading” to delay loading specific components until needed. On-demand loading, chunking, code splitting, and dynamic bundling are other names for this technology. Lazy loading divides large applications into smaller “chunks.” Only the necessary code bundles are loaded at initially, and the rest load dynamically as the user interacts with the program, avoiding the need to download everything.

This is accomplished in React.js by utilising the Suspense component and the lazy method. While Suspense is an integrated component that shows a fallback user interface (such as a loading message, spinner, or shimmer UI skeleton) while the dynamically imported component or data is still loading, the lazy function dynamically imports a component. To produce these more manageable, targeted code segments, this procedure is utilised in tandem with build systems such as webpack.

Lazy Loading in React.js
Lazy Loading in React.js

For example, a shopping cart component in an e-commerce application might not be included in the original bundle because it might only load when the user navigates to the cart page. Lazy loading might present issues like extra server communication and possible SEO effects, and it may not be appropriate for small-scale apps, despite its advantages for bigger ones.

Why Lazy Loading is Important

For large-scale apps in particular, lazy loading is an essential design technique for maximising the efficiency of React applications. Instead of loading the entire application at once, it enables you to load certain sections of it on demand, which means that modules and components are fetched only when the user requests them. Because it divides a single, big application bundle into smaller, easier-to-manage pieces, this procedure also known as code splitting, chunking, dynamic bundling, or on-demand loading is essential.

Lazy loading is primarily important because it can drastically cut down on the initial load time and bundle size. This reduces the workload on the browser, improves application performance in low-bandwidth situations, and ultimately improves the user experience during the initial loading phase. Functionality like a shopping cart, for instance, may be in a different bundle and only load when the visitor visits the cart page.

Lazy loading has several advantages:

  • Decreased the bundle size that must be downloaded up front, which shortened the initial load time.
  • The performance of the application, especially when there is a lack of bandwidth.
  • Improved initial loading experience because users are presented with a working user interface sooner.
  • Only the code needed for the current user interaction is loaded, resulting in optimised utilisation.

Even while slow loading is very advantageous for large-scale applications, small-scale applications could not noticeably benefit from it.

Implementing Lazy Loading with React.js

To make asynchronous component loading and code splitting easier, React comes with built-in features called lazy and suspense.

You can dynamically import a component using the lazy function. A dynamic import() statement for your component is returned by calling lazy and passing it a function rather than statically importing a component at the top of your project. By doing this, React is instructed to load the component only after rendering.

While its lazy-loaded progeny load, the integrated React component Suspense displays a backup user interface. This improves loading without a blank webpage. You may display any React.js element as a loading indicator by using Suspense’s fallback parameter.

Code Example: Lazy Loading a River Information Component

Let’s look at an example of lazy loading in action a RiverInformation component that asynchronously retrieves data is lazy-loaded.

import React from 'react';
const RiverInformation = () => {
  const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));
   const fetchData = async () => {
    await wait(2000); 
    return "This is a placeholder for information about a river.";
  };
  const [riverData, setRiverData] = React.useState(null);
  React.useEffect(() => {
    fetchData().then(data => setRiverData(data));
  }, []);
  if (!riverData) {
    return <div>Fetching river data...</div>;
  }
  return (
    <div style={{ padding: '20px', border: '1px solid #ccc', marginTop: '20px' }}>
      <h2>River Information</h2>
      <p>{riverData}</p>
      <p>This component was loaded on demand!</p>
    </div>
  );
};
export default RiverInformation;

Output:

River Information

This is a placeholder for information about a river.
This component was loaded on demand!

Explanation of the Code

Import lazy and Suspense: In order to begin, you must import Suspense and Lazy from the React library.

Define Lazy-Loaded Component: Define Lazy-Loaded Component RiverInformation is now defined using const RiverInformation = lazy(() => import(…)); in instead of a standard import line. Lazy receives an arrow function that calls the component file dynamically using import().

Webpack Chunk Naming: “RiverInformation” */ is a webpack magic comment that appears inside the import() function. The created JavaScript chunk for this component is named “RiverInformation” rather than an arbitrary number by webpack, the default bundler used by Create React App, as instructed by this remark. This enhances readability and debugging in the Network tab of the browser.

Wrap with Suspense: There is now a <Suspense> component rendered inside the RiverInformation component.

fallback Prop: The suspense element necessitates a fallback prop. This prop’s value is the React element that will be shown while the lazy-loaded component is still being downloaded and properly processed. Here we have a straightforward <div>Loading Component</div>.

This changed code will only fetch the JavaScript code for the RiverInformation component from the server when show is true and the component has to be presented. It will show the “Loading Component” notice as it loads. After loading, the fallback message will be replaced with the RiverInformation component.

This method guarantees speedier initial page loads because users only download the code for the parts they require right away. To make the user experience more responsive and seamless, additional components are loaded when users explore or interact with the program.

Conclusion

To sum up, lazy loading in React.js is an effective optimisation method that greatly enhances application speed by loading components only when required instead of combining them all at once. This method improves user experience, speeds up page loads, and decreases the initial bundle size particularly for large-scale applications with intricate functionality. Developers may easily create asynchronous component loading by utilising React’s built-in lazy and suspense components.

This allows the interface to remain dynamic by presenting fallback UI elements while the loading process is underway. Lazy loading is still a useful technique for enhancing perceived performance, cutting down on bandwidth usage, and guaranteeing users can engage with important app features sooner, even though the advantages are most apparent in larger projects.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index