How to implement lazy loading in React.js



Image not found!!

Lazy loading in React.js is a technique used to defer the loading of certain components until they are actually needed. This can help improve the initial loading time of your application by only loading the necessary code when it is required. React provides a feature called React.lazy() that makes it easy to implement lazy loading. Additionally, React Suspense can be used to handle loading states.

Here's a basic example of how you can implement lazy loading in React:

  1. Using React.lazy() and Suspense:

    First, make sure your React version is 16.6 or higher, as React.lazy() and Suspense were introduced in React 16.6.

    jsx
    // Import necessary modules import React, { lazy, Suspense } from 'react'; // Create a lazy-loaded component using React.lazy const LazyComponent = lazy(() => import('./LazyComponent')); // Create a component that uses the lazy-loaded component const MyComponent = () => ( <div> <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> </div> ); export default MyComponent;

    In this example, LazyComponent is a component that will be loaded lazily when it is actually rendered. The Suspense component is used to specify a fallback UI while the lazy component is being loaded.

  2. Using React Loadable (Alternative):

    You can also use a third-party library like React Loadable for lazy loading. React Loadable provides more control over the loading process.

    First, install React Loadable:

    bash
    npm install react-loadable

    Then, use it in your component:

    jsx
    import React from 'react'; import Loadable from 'react-loadable'; const LoadableComponent = Loadable({ loader: () => import('./LazyComponent'), loading: () => <div>Loading...</div>, }); const MyComponent = () => ( <div> <LoadableComponent /> </div> ); export default MyComponent;

    Here, LoadableComponent is the lazy-loaded component, and the loading prop specifies the component to render while the lazy component is loading.

Choose the approach that best fits your project and preferences. Keep in mind that lazy loading is particularly useful for optimizing large applications with many components, as it can reduce the initial bundle size and improve performance.