DEV Community

Cover image for React Apps with Code Splitting
TenE
TenE

Posted on

React Apps with Code Splitting

Introduction

Code splitting is a technique that improves the performance of React applications by breaking the bundle into smaller chunks that are loaded only when needed. This helps reduce the initial load time and enhances the user experience.

Why Use Code Splitting?

  • Improved Performance: Reduces initial JavaScript payload size.
  • Faster Load Times: Loads only necessary code when required.
  • Efficient Resource Utilization: Minimizes unused code execution.

Implementing Code Splitting in React

React provides built-in support for code splitting via lazy and Suspense.

1. Using lazy for Lazy Loading

  • The React.lazy or lazy function allows you to load a component dynamically only when it is needed. Example:
import React, { Suspense, lazy } from "react";
const LazyComponent = lazy(() => import("./LazyComponent"));

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

export default App;
Enter fullscreen mode Exit fullscreen mode

2. Code Splitting with React Router

When using React Router, you can split code by dynamically importing route components.

Example:

import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";

const Home = lazy(() => import("./Home"));
const About = lazy(() => import("./About"));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </Suspense>
    </Router>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

3. Using Webpack's Dynamic Imports

Webpack supports dynamic imports using import(), which can be used to split code.

Example:

function loadComponent() {
  import("./DynamicComponent").then((module) => {
    const Component = module.default;
    // Render component dynamically
  });
}
Enter fullscreen mode Exit fullscreen mode

Best Practices for Code Splitting

  • Split at Route Level: Load components dynamically for different pages.
  • Lazy Load Large Dependencies: Use lazy for libraries like charts or modals.
  • Optimize Bundle Splitting: Use Webpack's SplitChunksPlugin for optimized splitting.
  • Use Suspense for Fallback UI: Provide user-friendly loading indicators.

Conclusion

Code splitting is an essential technique to improve performance in React apps. By leveraging lazy, Suspense, and dynamic imports, you can enhance the user experience by reducing initial load times and loading components efficiently.

Top comments (0)