Open In App

How to Implement Code Splitting in React ?

Last Updated : 22 Mar, 2024
Like Article

In this article, we will learn about Implementing React code splitting via React.lazy() and Suspense improves app performance by loading code asynchronously and on-demand.

What is Code Splitting?

Code splitting is a technique used to split a large JavaScript bundle into smaller chunks, which are loaded asynchronously. By only loading the code that is needed at the time, code splitting reduces the initial load time of the application, leading to faster page rendering and improved user experience.

Approach to implement Code Splitting:

  • React.lazy(): In the `App.js` file, we use `React.lazy()` to lazily load the `LazyComponent`. The `import()` function is passed as an argument to `React.lazy()`, which dynamically imports the component. It returns a `Promise` for the module containing the component.
  • Suspense: We wrap the `<LazyComponent />` with the `<Suspense>` component. Suspense allows us to specify a loading indicator (fallback) while the lazily loaded component is being fetched. In this example, we display a simple “Loading…” message as the fallback.
  • Asynchronous Loading: When the `App` component mounts, React starts fetching the code for `LazyComponent` asynchronously. While the component is being loaded, the `Suspense` component displays the loading indicator.
  • Rendering LazyComponent: Once the code for `LazyComponent` is fetched and loaded, React renders the `LazyComponent` in place of the `<Suspense>` component.

Example of Code Splitting in React

Example: Suppose we have a React application with a main component `App` and a dynamically loaded component `LazyComponent`.

// App.js
import React,
} from 'react';

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

const App = () => (
        <h1>React Code Splitting Example</h1>
        <Suspense fallback={<div>Loading...</div>}>
            <LazyComponent />

export default App;
// LazyComponent.js
import React from 'react';

const LazyComponent = () => (
        <h2>Lazy Loaded Component</h2>
            This component was loaded
            asynchronously using code splitting.

export default LazyComponent;

Steps to Run the App:

npm start





Utilizing React.lazy() and Suspense for code splitting is an effective method to optimize React app performance, asynchronously loading components to reduce initial load time and enhance user experience. However, exercise caution in code splitting, balancing bundle size and network requests for optimal performance.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads