Skip to content

How to Lazy Load Component in React

In this post, we will learn how to lazy load a component in React.

Lazy loading is a technique used to defer the loading of non-essential resources at the time of the initial page load. This can help improve the performance of your application by reducing the initial load time and only loading components when they are needed.

React.lazy was introduced in React 16.6.0, which was released on October 23, 2018. It allows you to dynamically import a component and render it only when it is needed.

React.lazy works in combination with Suspense, which provides a fallback UI while the lazy-loaded components are being fetched.

Example Using React.lazy and Suspense in React

import React, { Suspense } from 'react';

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

const App = () => {
  return (
    <div>
      <h1>Lazy Loading Example</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <LazyLoadedComponent />
      </Suspense>
    </div>
  );
}

export default App;

In the example above, we use the React.lazy function to dynamically import the LazyLoadedComponent when it is needed. We then wrap the component in a Suspense component with a fallback prop that will be displayed while the component is loading.