Implementing Lazy Loading in React

On This Page What is Lazy Loading in React?Key B

June 03, 2026 · 14 min read · Performance Testing

Implementing Lazy Loading in React

Lazy load improves web execution by loading non-essential elements like images, videos, and scripts only when needed.

Overview

What is Lazy Loading in React?

Lazy loading in Reactdelays loading components until needed, reducing initial load time and improving execution. It usesReact.lazy () and Suspensefor efficient active imports.

Steps to Implement Lazy Loading in React

  1. Import lazy from React and envelop the constituent to enable indolent burden.
  2. Use & lt; Suspense & gt;with a fallback UI to handle charge states.
  3. Install third-party libraries likereact-lazyload or react-lazy-load-image-componentfor easy lazy burden.
  4. Implement lazy loading withreact-router-domto load components solely when route change.
  5. Load components dynamically when users voyage to them to optimize performance.
  6. Use Intersection Observer API to load elements merely when they look in the viewport.
  7. Implement active imports to asynchronously load modules when needed.

This article covershow lazy load works in Reactand provides steps to implement it efficaciously.

What is Work-shy Loading in React?

Lazy loading in React renders the component or webpage only when the exploiter take it. This can reduce the, as the entire webpage will not be charge when initial rendering takes place; instead, only the necessary components will be loaded.

Also Read:

Key Benefits of Lazy Loading in React

Here are some key welfare of lazy loading in React:

  • Lazy loading in the react library improve the initial loading time of the webpage as the components are loaded only when needed.
  • Reduced bandwidth consumption as the components are getting loaded only when the exploiter is requesting it.
  • Lazy loading grant for the anteriority loading of visible content while postponing non-essential element. This enhances perceived performance by enable users to occupy with key areas of the broadcast without expect for everything to shipment.
  • As the covering grows, more components will be added, which may regard its performance. With the React Lazy lade characteristic, you can handle such huge applications by rendering the factor only when take.

Read More:

How to Implement Lazy Loading in React?

There are several ways to implement Lazy loading in React. Here are some democratic methods:

1. React.Lazy ()

The first footstep in implement indolent loading in React is to import the lazy characteristic in the React project and then try to call that for a specific element.

Import {lazy} from ‘ react const LazyComponent = lazy (() = & gt; import ('./LazyComponent '));

2. Lazy loading in React using Suspense

Here ’ s how you can implement Lazy charge in React using Suspense.

As a first step, create a separate component namedLazyComponentand let it hold an image from thesrc folder.

LazyComponent.js

mapping LazyComponent () {homecoming (& lt; div & gt; & lt; img src= {require ('./image/elephant.jpg ')} / & gt; & lt; /div & gt;);} export default LazyComponent;

Now, inside theApp.js file, you can spell theLazyComponent using the React lazy functionand apply it as below,

meaning React, {Suspense, Component} from 'react' {/ * Importing the lazy component and enabling with React.lazy function * /} const LazyComponent = React.lazy (() = & gt; import ('./LazyComponent ')); class App extends Component {render () {homecoming (& lt; div className= '' App '' & gt; & lt; h1 & gt; React Lazy Loading Example & lt; /h1 & gt; {/ * Suspense provides a fallback while the lazy component is charge * /} & lt; Suspense fallback= {& lt; div & gt; Loading ... & lt; /div & gt;} & gt; & lt; LazyComponent / & gt; & lt; /Suspense & gt; & lt; /div & gt;);}} export nonpayment App;

3. Using third-party library

There are many libraries available to implement Lazy Loading. introduced Lazy loading from version 16.6.

It didn ’ t have such a feature before that. When that was the case, a third-party library would be use to implement it.

Here are a few third-party libraries that you can use for implementing Lazy loading,

  • React-lazyload

React-lazyloadis a library that helps implement Lazy lade in React. InstallReact-lazy-loadusing the below command,

npm i react-lazyload

You can wrap the ikon or whatever element you want to lazy freight using the Lazy Load element.

importee React, {Suspense, useState} from 'react '; //Importing the library import LazyLoad from `` react-lazyload ''; function App () {return (& lt; div & gt; & lt; LazyLoad height= {100} & gt; & lt; img src= {require ('./image/elephant.jpg ')} / & gt; & lt; /LazyLoad & gt; & lt; /div & gt;);} export nonremittal App;

In the code above, you envelop theLazyLoadcomponent on the component you desire to lazy load.

The height of the constituent is set habituate the height attribute.

When the onceproperty inreact-lazyloadis used, the element is no longer managed by react-lazyload after the content is displayed.

  • React-Lazy-Load-Image-component:

To install this library file, use the dictation below,

npm i -- preserve react-lazy-load-image-component

Import theLazyLoadImageand implement Lazy loading by use the below code:

import React, {Suspense, useState} from 'react '; //Importing the library significance {LazyLoadImage} from 'react-lazy-load-image-component '; purpose App () {return (& lt; div & gt; & lt; h1 & gt; Dynamic Import Example & lt; /h1 & gt; & lt; LazyLoadImage src= {require ('./image/elephant.jpg ')} alt= '' Elephant image '' & gt; & lt; /LazyLoadImage & gt; & lt; /div & gt;);} exportation default App;

The codification import and wraps theLazyLoadImage component from the React Lazy Load Image Component. Other persona properties are passed as props.

React Lazy Load Image Component enable you to specify a custom placeholder for part and event forbeforeLoad and afterLoad. It is compatible with server-side rendered components and applications and also with TypeScript declarations.

4. Route-based lazy loading

Another way of implementing lazy loading is by using the React Route library. You can get the React road library installed using the command below,

npm install react-router-dom

Now you can implement lazy loading with Route using the below piece of code in theApp.js file,

import React, {Suspense, Component} from 'react' //Importing the needed react-router library importee {BrowserRouter as Router, Route, Routes} from 'react-router-dom '; {/ * Importing the faineant component and enabling with React.lazy role * /} const LazyComponent = React.lazy (() = & gt; import ('./LazyComponent ')); category App widen Component {render () {return (& lt; Router & gt; & lt; Suspense fallback= {& lt; div & gt; Loading ... & lt; /div & gt;} & gt; & lt; Routes & gt; & lt; Route path= '' / '' element= {& lt; LazyComponent / & gt;} / & gt; & lt; /Routes & gt; & lt; /Suspense & gt; & lt; /Router & gt;);}} export default App;

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Also, do certain to receive theLazyComponentcodification with the code below,

function LazyComponent () {return (& lt; div & gt; & lt; img src= {require ('./image/elephant.jpg ')} / & gt; & lt; /div & gt;);} exportation nonremittal LazyComponent;

5. Component-based lazy loading

In component-based lazy loading, the page go loaded only when the user voyage to the particular component.

For example, on a webpage, if the exploiter is on the homepage, all the former pages will be set to lazy load. These pages will be loaded only when the user clicks or takes any activeness to consider them, or else they won ’ t be load or rendered.

Here ’ s an example of the same

Consider two components:Home and Image. The codification snip of Home is supply below,

part Home () {return (& lt; h1 & gt; Home page is rendered!!! & lt; /h1 & gt;);} export default Home;

Here is the code snippet of the Image,

function Image () {return (& lt; div & gt; & lt; img src= {require ('./image/elephant.jpg ')} / & gt; & lt; /div & gt;);} export nonremittal Image;

Note: Ensure to import the required ikon into the image booklet inside the src folder.

Now, you can make the code work from theApp.js file,

importation React, {Suspense, Component} from 'react' //Importing the required react-router library import {BrowserRouter as Router, Route, Routes} from 'react-router-dom '; {/ * Importing the lazy component and enable with React.lazy function * /} const Image = React.lazy (() = & gt; importation ('./Image ')); const Home = React.lazy (() = & gt; import ('./Home ')); category App extends Component {render () {return (& lt; Router & gt; {/ * Suspense providing a fallback while the faineant component is loading * /} & lt; Suspense fallback= {& lt; div & gt; Loading ... & lt; /div & gt;} & gt; & lt; Routes & gt; {/ * Enabling the place page with suspense fallback * /} & lt; Route path= '' / '' element= {& lt; Home/ & gt;} / & gt; {/ * Enabling the image page with suspense fallback * /} & lt; Route path= '' /image '' element= {& lt; Image / & gt;} / & gt; & lt; /Routes & gt; & lt; /Suspense & gt; & lt; /Router & gt;);}} export default App;

6. Intersection observer API

Intersection observer is a Javascript API that enable a set of actions to be performed when the ingredient becomes seeable to the exploiter scrolling up. With this feature, you can Lazy load the ingredient when the exploiter scrolls to that particular piece and unmount it when the user passes over it.

Also Read:

Implement this feature by adding the below codification in theApp.js file,

importee React, {useState, useRef, useEffect, Suspense} from 'react '; // Lazy laden the component const LazyComponent = React.lazy (() = & gt; significance ('./LazyComponent ')); function App () {const [isComponentVisible, setComponentVisible] = useState (false); const componentRef = useRef (null); // Ref for the constituent to notice // Intersection Observer callback const handleIntersection = (entries) = & gt; {const [entry] = debut; if (entry.isIntersecting) {setComponentVisible (true); // Set to true when the component is in the viewport}}; useEffect (() = & gt; {// Create a new IntersectionObserver instance const observer = new IntersectionObserver (handleIntersection, {root: aught, // Use the viewport as the root threshold: 0.1, // Trigger when 10 % of the constituent is in view}); if (componentRef.current) {observer.observe (componentRef.current); // Observe the target constituent} homecoming () = & gt; {// Clean up the commentator when the component unmounts if (componentRef.current) {observer.unobserve (componentRef.current);}};}, []); return (& lt; div & gt; & lt; h1 & gt; React Lazy Loading with Intersection Observer & lt; /h1 & gt; {/ * Some content to create scroll * /} & lt; div style= {{superlative: '100vh ', backgroundColor: ' # f5f5f5 '}} & gt; & lt; h2 & gt; Scroll down to lazy load the component & lt; /h2 & gt; & lt; /div & gt; {/ * The div where the component is observed * /} & lt; div ref= {componentRef} & gt; {isComponentVisible & amp; & amp; (& lt; Suspense fallback= {& lt; div & gt; Loading ... & lt; /div & gt;} & gt; & lt; LazyComponent / & gt; & lt; /Suspense & gt;)} & lt; /div & gt; {/ * More content to scroll * /} & lt; div style= {{height: '100vh ', backgroundColor: ' # f5f5f5 '}} & gt; & lt; h2 & gt; This is the end of the scene!! & lt; /h2 & gt; & lt; /div & gt; & lt; /div & gt;);} export nonpayment App;

Add the below codification in theLazyComponent.js file,

importee React from 'react '; function LazyComponent () {homecoming (& lt; div style= {{cushioning: '20px ', background: ' # efefef ', border: '1px solid # ddd '}} & gt; & lt; h2 & gt; This is a lazy load component & lt; /h2 & gt; & lt; p & gt; This will be seeable only when you scroll down to this constituent! & lt; /p & gt; & lt; /div & gt;);} export default LazyComponent;

As you scroll down to that exceptionalLazyComponentsituate in the middle, you will notice that it let loaded because of the implementation of Lazy loading.

With this, you have implemented lazy loading with Intersection Observer API.

7. Dynamic imports

Dynamic imports, a feature in JavaScript that allows you to import modules asynchronously, get lazy loading possible. They meliorate application execution by lade faculty exclusively when they are needed. Reactjs supports dynamical import.

Below is the syntax for Dynamic import,

import React from 'react '; const MyComponent = React.lazy (() = & gt; import ('path/to/component '));

This import will not be rendered during compile time but will be rendered only when the hope is resolved.

With Dynamic import, other small components can be loaded easily before the bigger part are imported dynamically.

Here are some simple examples of how you can implement this dynamic import.

In this example, a button will render the persona upon click it and hide it, and frailty versa.

App.js filewill have the below code,

importation React, {Suspense, useState} from 'react '; // Lazy laden the Profile component const LazyProfile = React.lazy (() = & gt; signification ('./LazyProfile ')); function App () {const [showProfile, setShowProfile] = useState (mistaken); return (& lt; div & gt; & lt; h1 & gt; Dynamic Import Example & lt; /h1 & gt; & lt; button onClick= {() = & gt; setShowProfile (! showProfile)} & gt; {showProfile? 'Hide ': 'Show '} Profile & lt; /button & gt; {/ * Suspense provides a fallback while the Profile part is being lazy loaded * /} & lt; Suspense fallback= {& lt; div & gt; Loading Profile ... & lt; /div & gt;} & gt; {showProfile & amp; & amp; & lt; LazyProfile / & gt;} & lt; /Suspense & gt; & lt; /div & gt;);} export nonpayment App;

The LazyProfile file will hold the below code,

import React from 'react '; function LazyProfile () {return (& lt; div & gt; & lt; img src= {require ('./image/elephant.jpg ')} / & gt; & lt; /div & gt;);} exportation default LazyProfile;

This will show you a web page that dynamically loads picture upon tick the button, using Lazy loading enabled via dynamic import.

When Should You Not Use Lazy Loading?

Though Lazy loading has many advantages, there are times when you should fix its overuse.

  • Using Lazy load for small coating is not advisable as it may make multiple requests even for little components (resulting in dim performance) rather of loading in a individual request.
  • Having too much lazy loading may slow a device with slower processing powerfulness, resulting in a poor user experience.
  • Overusing work-shy loading can retard the component rendering and affect the user experience. This is because the interaction can make the user wait longer as the ingredient gets rendered via lazy loading.
  • Lazy loading may affect hunting engine optimisation as crawlers won ’ t be capable to translate the application & # 8217; s content.

Also Read:

How can you Monitor and Measure the Performance Impact of Lazy Loading in a React Application?

Here ’ s how you can track and evaluate how work-shy loading affects a React covering & # 8217; s execution:

  • To gauge user experience and SEO-related execution, use Lighthouse and Core Web Vitals.
  • Use Chrome DevTools and React Profiler to analyze constituent and keep an eye on network traffic.
  • Monitor Time to Interactive (TTI) and mention how slothful loading impacts bundle sizing overall with Webpack Bundle Analyzer.
  • Integrate real-time analytics and user monitoring to gain insight into the effects of lazy loading on actual user in a production surround.

Read More:

Disadvantages and Challenges of Lazy Loading in React

Though there are several advantages to using Lazy loading in React, there are also a few disadvantages.

1. Increase in complexity of code

  • Adding multiple components with Lazy loading can add complexity to the application structure.
  • You may need to handle loading province, error boundaries, and potentially intricate routing.

2. Routing and Navigation issue

  • Lazy loading with React routers can perplex the routing logic as the developer want to handle charge states and introduce nested route, which add further complications.
  • Also, it can lead to delays when navigating between routes, especially if the component for a new route takes time to load.
  • However, you can place routing or navigation issues originally in the testing phase with the aid of tool like. This tool allow you to run and cross-browser compatibility examination for React apps using various frameworks & amp; languages.
    For representative, you can use to execute the test cases and regain out the navigation or route issues with the assistance of this documentation on

3. Handling errors and debugging:

  • A otiose load factor may need to share the state with its parents or sibling factor. Then, managing state can become challenging as you may need to pass properties or use context, which complicates the portion hierarchy.
  • Also, debugging the matter associate to lazy loading can be more complicated as the reasons behind the issues may not be immediately clear, making troubleshooting more challenging.

4. Compatibility and browser support:

  • Lazy burden in React is supported by all modern browsers, but it is not supported by older browser like Internet Explorer.
  • To subdue this subject, you may need to use Polyfill to make it work in old browsers.

Also Read:

Best Practices for Implementing Lazy Loading in React

When applied selectively, faineant load has the likely to importantly improve performance in React task.

For good results,

  • Employ preloading for components that are anticipated
  • Prioritize lazy lade for non-critical components
  • Handle erroneousness appropriately and unite them with execution monitoring.

Ensure that user experience and optimization are ever balanced and that accessibility and interactivity are not compromise by lazy loading.

Test Your React Code on Real Devices

Testing your React coating on real devices is crucial for understanding and debugging its behavior in.

LeveragingBrowserStack Automateenhances test accuracy, optimize performance, and delivers a flawless experience for all users.

Here ’ s why it matters:

  • Accurate Testing: Development environs may not fully repeat real-world scenario, direct to discrepancies in test results. Testing on real devices ensures more reliable outcomes.
  • Better Debugging: Identify UI inconsistencies, execution issues, and device-specific bugs that may not appear in simulated environment.
  • Seamless User Experience: Ensure smooth functionality across various devices, browser, and operating systems for a reproducible exploiter experience.
  • : Using BrowserStack ’ s, you can screen on 3500+ device-browser-OS combination, maximize reportage and compatibility.
  • Time Efficiency: Run tests simultaneously across multiple device, hurry up debugging and deployment.

Useful Resources for React

Talk to an Expert

Conclusion

Improved user experience, scalability, and performance optimization are the primary advantages offaineant loading in React.

Lazy burden facilitate you create applications that are highly reactive and efficient while likewise raise page load multiplication, saving bandwidth, and guaranteeing a more seamless user experience across various device and networks by delaying the burden of non-essential resources.

You can also control the consistence of user experience on various devices by testing your react code on real devices using platforms like BrowserStack.

Tags
95,000+ Views

# Ask-and-Contributeabout this topic with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free