React - Lazy

React Mapping Html Javascript

About

The lazy function 1) implements lazy loading. (ie it will let you defer loading component’s code until it is rendered/executed for the first time)

It's part of code splitting meaning that the build step will create an extra module that will be dynamically loaded when the code run

How to use it?

Step 1: Make your component Lazy

Default exports

React.lazy currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that reexports it as the default.

Good:

export { MyComponent as default } from "./ManyComponents.js";

Bad:

// ManyComponents.js
export const MyComponent = /* ... */;
export const MyUnusedComponent = /* ... */;

Wrap your component with Lazy

Before:

import OtherComponent from './OtherComponent';

After:

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

The wrap internally uses the dynamic import statement that triggers code splitting in most bundlers.

Step 2: Make your component Lazy aware

Because your component will be now Lazy loaded, you should wrap it inside a reference/react/Suspense component to add fallback content. It will be used as a loading indicator while the user is waiting for the lazy component to load.

import React, { Suspense } from 'react';

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

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <OtherComponent />
      </Suspense>
    </div>
  );
}

Example: Route-based code splitting

With the React Router library

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./routes/Home'));
const About = lazy(() => import('./routes/About'));

const App = () => (
  <Router>
    <Suspense fallback={<div>Loading...</div>}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/about" element={<About />} />
      </Routes>
    </Suspense>
  </Router>
);







Share this page:
Follow us:
Task Runner