Open In App

How to Implement Code Splitting in React ?

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:

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,
{
    Suspense
} from 'react';

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

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

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

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

export default LazyComponent;

Steps to Run the App:

npm start

Output:

Untitled-design-(34)

Output

Conclusion:

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.

Article Tags :