Lazy Loading

Introduction

What is lazy loading in React?

  • It is an optimization technique which prevents the entire application from loading at once. Instead the elements crucial to the UI get to be loaded first, while less important parts of the code will get loaded later. This can be useful when dealing with pages with large amounts of content which may cause performance issues.

Reference

lazy(load)

Call lazy outside your components to declare a lazy-loaded React component:

import { lazy } from 'react';

const Cards = lazy(() => import('../components/Cards'));

Usage

Lazy-loading components with Suspense

<Suspense fallback={<Loadings />}>
      {
        products.map((product) => (
          <Cards
            key={product.id}
            url={product.images[0]}
            desc={product.title}
            id={product.id}
            price={product.price}
          />
        ))
      }
</Suspense>

The output of above code will render list of product from APIs to Card Component with lazy loaded. It meant if list of product not yet response, it will show Loading Components.

The loading show, while waiting data response from API

Waiting Data

The output when data is ready.

Data Ready

💡 Note:

Last updated