DEV Community

Safal Bhandari
Safal Bhandari

Posted on

Lazy Loading in React: Boosting Performance by Loading Code on Demand

When a React app grows, bundling all its code into a single file can slow down the initial load. Lazy loading solves this by splitting the code into chunks and loading parts only when needed — improving load times and user experience.


What is Lazy Loading?

Lazy loading (a.k.a. code splitting) is a performance optimization technique where parts of your app are loaded on demand rather than all at once.

In React, we use:

  • React.lazy() to dynamically import components.
  • Suspense to show a fallback (like a loader) while the component loads.

Basic Lazy Loading Example

import React, { Suspense } from 'react';

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

export default function App() {
  return (
    <div>
      <h1>My App</h1>
      <Suspense fallback={<div>Loading...</div>}>
        <About />
      </Suspense>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

How it works:

  • React.lazy() dynamically imports the component.
  • It’s loaded only when rendered.
  • Suspense provides a fallback UI until the component is ready.

Lazy Loading with react-router-dom

When combined with routing, lazy loading ensures each page’s code loads only when the user navigates to it.

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

const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));

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

export default App;
Enter fullscreen mode Exit fullscreen mode

Advantages here:

  • /about component is loaded only when the user visits /about.
  • Reduces the size of the initial JavaScript bundle.

Why Use Lazy Loading?

  • Faster initial load — users see your app sooner.
  • Better performance on slow networks.
  • Efficient bandwidth usage — load only what’s needed.

Things to Keep in Mind

  • Always wrap React.lazy() components with Suspense.
  • Lazy loading is best for routes, large components, or rarely used features.
  • For SEO-heavy apps (like blogs), lazy loading might delay content for crawlers unless handled carefully.

Key takeaway:
Lazy loading in React — especially when combined with react-router-dom — is a must-have optimization for large apps. It makes apps faster by loading components only when they’re actually needed.


Top comments (0)