DEV Community

Cover image for Optimizing React Apps With Code Splitting and Lazy Loading
HexShift
HexShift

Posted on • Edited on

Optimizing React Apps With Code Splitting and Lazy Loading

Optimizing React Apps With Code Splitting and Lazy Loading

Large React applications can become sluggish if the JavaScript bundle grows too big. Code splitting and lazy loading are powerful techniques to break your app into smaller chunks, improving load times and performance. Here’s how to apply them effectively.

Why Code Splitting?

React apps are often bundled into a single large JavaScript file. This increases initial load time. Code splitting breaks that file into smaller pieces that load only when needed.

Step 1: Use React.lazy and Suspense

React provides built-in support for code splitting using React.lazy and Suspense. Here's a basic setup:

import React, { Suspense } from "react";

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

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

export default App;

This tells React to split HeavyComponent into its own bundle, which loads only when it’s rendered.

Step 2: Dynamic Imports for Routes

For routing-based apps (like with React Router), you can lazy load entire routes:

import { BrowserRouter, Routes, Route } from "react-router-dom";
const Home = React.lazy(() => import("./pages/Home"));
const About = React.lazy(() => import("./pages/About"));

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

Step 3: Combine With Webpack or Vite

Modern bundlers like Webpack and Vite handle code splitting automatically when using dynamic imports. Just make sure your setup supports ES modules and dynamic import() syntax.

Bonus: Preloading for UX

You can preload modules to make navigation smoother:

const About = React.lazy(() => import(/* webpackPrefetch: true */ "./pages/About"));

This tells Webpack to download the chunk in the background.

Conclusion

Code splitting and lazy loading are essential tools for building fast, efficient React applications. With just a few lines of code, you can reduce bundle size and significantly improve the user experience.

For a much more extensive guide on getting the most out of React portals, check out my full 24-page PDF file on Gumroad. It's available for just $10:

Using React Portals Like a Pro.

If this post helped you, consider supporting me: buymeacoffee.com/hexshift

Top comments (0)