DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Code Splitting with React.lazy: Enhance Your App’s Performance

Code Splitting with React.lazy in React

Code Splitting is a technique to optimize the performance of React applications by breaking down the JavaScript bundle into smaller chunks. React provides React.lazy as a built-in way to implement code splitting at the component level. This allows you to load parts of your application dynamically as they are needed.


How Code Splitting Works with React.lazy

  1. Dynamic Import: Uses ES6 import() to load components dynamically.
  2. Smaller Bundles: Breaks down the app into smaller bundles, reducing the initial load time.
  3. Asynchronous Loading: Loads components asynchronously only when required.

Syntax

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

function App() {
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </React.Suspense>
  );
}
Enter fullscreen mode Exit fullscreen mode
  • React.lazy: Dynamically imports the specified component.
  • Suspense: Provides a fallback UI while the component is being loaded.

Example 1: Basic Code Splitting with React.lazy

Without Code Splitting

import React from "react";
import HeavyComponent from "./HeavyComponent";

function App() {
  return (
    <div>
      <h1>Main App</h1>
      <HeavyComponent />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In this approach, the entire HeavyComponent is bundled with the main app, even if it’s not immediately needed.

With Code Splitting

import React, { Suspense } from "react";

const HeavyComponent = React.lazy(() => import("./HeavyComponent"));

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Now, HeavyComponent is only loaded when it is rendered. This reduces the size of the initial bundle.


Example 2: Code Splitting in Routes

Code splitting works seamlessly with React Router to load route components dynamically.

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

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

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Benefits:

  • Each route component (Home, About, Contact) is loaded only when the corresponding route is accessed.

Example 3: Lazy Loading Multiple Components

Lazy-load multiple components in a single app with logical splitting.

import React, { Suspense, useState } from "react";

const ComponentA = React.lazy(() => import("./ComponentA"));
const ComponentB = React.lazy(() => import("./ComponentB"));

function App() {
  const [showA, setShowA] = useState(false);
  const [showB, setShowB] = useState(false);

  return (
    <div>
      <button onClick={() => setShowA(true)}>Load Component A</button>
      <button onClick={() => setShowB(true)}>Load Component B</button>

      <Suspense fallback={<div>Loading...</div>}>
        {showA && <ComponentA />}
        {showB && <ComponentB />}
      </Suspense>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Error Handling with React.lazy

React doesn’t provide built-in error handling for failed imports. You can use an Error Boundary to handle such cases.

import React, { Suspense } from "react";

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

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  render() {
    if (this.state.hasError) {
      return <div>Error loading component</div>;
    }
    return this.props.children;
  }
}

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Best Practices for Code Splitting

  1. Split By Route or Feature: Break your app into logical chunks, such as routes or major features.
  2. Keep Fallbacks Minimal: Use lightweight fallback UIs like spinners or text messages.
  3. Monitor Bundle Size: Use tools like Webpack Bundle Analyzer to identify large components.
  4. Avoid Over-Splitting: Balance between the number of chunks and performance; too many chunks can lead to increased HTTP requests.

Tools to Enhance Code Splitting

  1. Webpack: Supports dynamic imports for code splitting.
  2. Vite: Offers fast builds and automatic code splitting.
  3. React Router: Enables easy integration with route-based lazy loading.
  4. React Loadable: A third-party library for enhanced control over lazy loading.

Conclusion

Code splitting with React.lazy is a powerful way to improve your app's performance. By dynamically loading components, you can reduce the initial load time and enhance the user experience. When combined with Suspense and proper error handling, it provides a robust solution for building efficient, scalable React applications.


Top comments (0)