Code Splitting with React.Suspense and React.lazy

Code Splitting with React.Suspense and React.lazy

In React applications, code splitting is an optimization technique that allows breaking up large JavaScript bundles into smaller, on-demand chunks. This helps reduce the initial load time. The primary tools for code splitting in React are React.Suspense and React.lazy().

React.Suspense

React.Suspense is a component that provides a way to display a fallback UI (like a spinner or loading message) while a part of your app is being lazily loaded. It is crucial when using React.lazy(), as it enables you to manage the loading state of lazily loaded components.

Basic Usage Example:

import React, { Suspense } from 'react';

<Suspense fallback={<div>Loading...</div>}>
  <LazyComponent />
</Suspense>        
In this example, if LazyComponent takes time to load, the fallback UI (“Loading...”) will be displayed until the component is fully loaded.

React.lazy

React.lazy() is a function used to dynamically import components only when they are needed. This enables "lazy loading" of components, meaning they are loaded when they are actually rendered, not when the entire app is initialized.

React.lazy() works seamlessly with React.Suspense, allowing you to load components asynchronously and show a fallback UI in the meantime.

Example Using React.lazy and React.Suspense:

import React, { lazy, Suspense } from 'react';

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

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

export default App;        
In this example, MyComponent will be loaded lazily only when it is required, and Suspense will display "Loading..." until MyComponent is available.

Benefits of Code Splitting

  • Improved Performance: Only the required code chunks are loaded at the moment they’re needed, leading to faster initial loading times.
  • Better User Experience: Users see feedback (such as a loading indicator) while waiting for components to load.
  • Reduced Bandwidth Consumption: By splitting the code into smaller parts, users only download what is necessary, conserving data usage.

Conclusion

Suspense manages the loading state, while React.lazy() enables efficient code splitting. Together, they provide a powerful way to optimize the performance of React applications.

To view or add a comment, sign in

More articles by Jins Kurian

Explore content categories