sajad torkamani

In a nutshell

The React.lazy function lets you dynamically load the bundle containing a component when the component is first rendered.

import React, { Suspense } from 'react';

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

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

In the above example, assuming you’re using a bundler like Webpack, a separate bundle will be created that contains the OtherComponent.js file.

This bundle will only be imported on the page when OtherComponent is first rendered. Dynamically loading components like this helps reduce the size of the main bundle that’s initally loaded.

Use Suspense to provide a fallback content

Suspense takes a fallback prop that will render whilst the component within is being loaded.

Sources

Tagged: React

Leave a comment

Your email address will not be published. Required fields are marked *