Subscribe
Lazy Loading Components in React: Techniques and Examples
5 mins read

By: vishwesh

Lazy Loading Components in React: Techniques and Examples

React is a popular JavaScript library for building web applications. It allows developers to create reusable components that can be used throughout the application. However, as the application grows in size, it can become slower to load. One way to optimize performance is by implementing lazy loading of components.

Lazy loading is a technique that loads only the necessary components when they are needed. This helps reduce the initial load time of the application and improves overall performance. In this article, we will explore the techniques and examples of lazy loading components in React.

What is Lazy Loading?

Lazy loading is a technique used in web development to defer the loading of non-critical resources until they are needed. This is done to reduce the initial load time of the application and improve performance.

In the context of React, lazy loading is used to load only the components that are needed at runtime. This can be particularly useful for large web applications that have many components.

Lazy Loading Components in React

In React, lazy loading of components can be achieved using the React.lazy() function. This function allows us to load a component lazily when it is needed.

Here is an example of how to use React.lazy():

javascriptCopy code

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

In this example, we are importing a component called MyComponent using the import() function. This function returns a Promise that resolves to the module containing the exported component. The React.lazy() function takes this Promise as an argument and returns a new component that can be rendered lazily.

The React.lazy() function also allows us to define a fallback component that can be rendered while the lazily loaded component is being loaded. Here is an example:

javascriptCopy code

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

In this example, we are using the Suspense component to specify a fallback component that will be rendered while the MyComponent component is being loaded. The Suspense component is a new feature in React 16.6 that allows us to declaratively specify a loading state for a component.

Techniques for Lazy Loading Components

There are several techniques that can be used for lazy loading components in React. In this section, we will explore some of the most common techniques.

Route-based Lazy Loading

Route-based lazy loading is a technique that involves loading only the components that are needed for a particular route. This can be particularly useful for large web applications that have many routes.

Here is an example of how to implement route-based lazy loading using the React.lazy() function:

javascriptCopy code

import { lazy } from 'react'``; import { Route } from 'react-router-dom'``; const HomePage = lazy``(() => import``(``'./pages/HomePage'``)); const AboutPage = lazy``(() => import``(``'./pages/AboutPage'``)); function App``() { return (    <div>      <Route exact path``=``"/" component``=``{HomePage} />      <Route path``=``"/about" component``=``{AboutPage} />    </div>  ); }

In this example, we are using the lazy() function to lazily load the HomePage and AboutPage components. We are then using the Route component from the react-router-dom library to specify the routes and components to be rendered.

Component-based Lazy Loading

Component-based lazy loading is a technique that involves loading only the components that are needed for a particular component. This can be particularly useful for large components that have many sub-components.

Here is an example of how to implement component-based lazy loading using the React.lazy() function:

javascriptCopy code

const SubComponent1 = React``.``lazy``(() => import``(``'./SubComponent1'``)); const SubComponent2 = React``.``lazy``(() => import``(``'./SubComponent2'``)); const SubComponent3 = React``.``lazy``(() => import``(``'./SubComponent3'``)); function MyComponent``() { return (    <div>      <h2>My Component</h2>      <Suspense fallback``=``{``<``div``>Loading...</div>}>        <SubComponent1 />        <SubComponent2 />        <SubComponent3 />      </Suspense>    </div>  ); }

In this example, we are using the lazy() function to lazily load the SubComponent1, SubComponent2, and SubComponent3 components. We are then using the Suspense component to specify a fallback component that will be rendered while the sub-components are being loaded.

Intersection Observer

Intersection Observer is a new API that allows us to observe when an element enters or exits the viewport. This can be particularly useful for lazy loading components that are below the fold.

Here is an example of how to use Intersection Observer to lazy load components:

javascriptCopy code

import { useEffect, useRef, useState } from 'react'``; function LazyComponent``() { const [isVisible, setIsVisible] = useState``(``false``); const ref = useRef``(``null``); useEffect``(() => { const observer = new IntersectionObserver``(([entry]) => { setIsVisible``(entry.isIntersecting);    });    observer.``observe``(ref.current); return () => {      observer.``unobserve``(ref.current);    };  }, []); return (    <div ref``=``{ref}``>      {isVisible && <h2>Lazy Component</h2>}    </div>  ); }

In this example, we are using the useEffect() hook to create a new IntersectionObserver and observe the ref element. When the element enters the viewport, the isVisible state is set to true and the component is rendered.

Conclusion

In this article, we explored the techniques and examples of lazy loading components in React. We saw how lazy loading can be used to optimize performance by loading only the necessary components when they are needed. We also explored the different techniques that can be used for lazy loading, such as route-based lazy loading, component-based lazy loading, and Intersection Observer.

By using these techniques, you can improve the performance of your React application and provide a better user experience for your users.

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories