Use React.lazy and Suspense to load components lazily, improving initial loading times and reducing the bundle size.

Mar 13, 2023

React.lazy and Suspense are two features in React that allow you to load components lazily, meaning they are only loaded when they are actually needed. This can help improve initial loading times and reduce the overall size of your bundle.

Here’s how it works:

React.lazy allows you to dynamically import a component as a separate chunk when it is actually needed, rather than loading it upfront with the rest of your application code. This means that the component will not be included in the initial bundle that is loaded when a user visits your site. Instead, it will be loaded separately when the component is actually needed.

To use React.lazy, you simply need to wrap the component you want to lazily load with a call to React.lazy, like this:

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

Here, we are using the import() function to dynamically load the component from a separate file called MyComponent.js. This file will be loaded separately from the initial bundle when the component is actually needed.

However, because the component is loaded lazily, it may take some time to load. This is where Suspense comes in.

Suspense is a component that allows you to display a fallback UI while a lazy-loaded component is being loaded. This helps improve the user experience by letting the user know that something is happening, rather than leaving them staring at a blank screen.

Here’s an example:

import React, { Suspense } from 'react';

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

function App() {
  return (
    <div>
      <h1>Welcome to my app!</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <MyLazyComponent />
      </Suspense>
    </div>
  );
}

export default App;

Here, we are using the Suspense component to display a “Loading…” message while the MyLazyComponent is being loaded. Once the component is loaded, it will be displayed in place of the fallback UI.

Conslusion

By using React.lazy and Suspense together, you can improve the performance of your React application by reducing the initial bundle size and improving the perceived loading times for your users.