What Is Code-Splitting in React.js?

Code-splitting in React

Code-splitting in React is a technique used to split your application's code into smaller chunks, which are loaded only when they are needed. This can significantly improve the initial loading time of your application, especially for larger applications with many components and dependencies.

There are a few ways to implement code-splitting in React. One common approach is using dynamic imports, which allow you to import modules asynchronously at runtime. Another approach is using React's React.lazy() function in combination with the Suspense component to lazily load components.

Let's go through each approach with some code examples.

Dynamic Imports

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [data, setData] = useState(null);

  useEffect(() => {
    // Dynamically import fetchData module only when component mounts
    import('./fetchData').then((module) => {
      module.fetchData().then((data) => {
        setData(data);
      });
    });
  }, []);

  return (
    <div>
      {data ? (
        <ul>
          {data.map((item, index) => (
            <li key={index}>{item}</li>
          ))}
        </ul>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default MyComponent;

In this example, the fetchData module is imported dynamically using the import() function. The fetchData module contains a function that fetches some data asynchronously.

The useEffect hook ensures that the data is fetched only once when the component mounts. This way, the fetchData module is only loaded when it's needed.

import React, { Suspense } from 'react';

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

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

export default App;

In this example, MyLazyComponent it is imported lazily using React.lazy(). The Suspense component is used to display a loading indicator while the component is being loaded. When MyLazyComponent it is needed (for example, when it's rendered by App), React will load it asynchronously.

Both approaches achieve code-splitting in React, allowing you to load only the necessary code chunks when they are needed, thus improving the performance of your application.