reactjs
/

React Lazy Loading – Optimizing Bundle Size

Last Sync: Today

On this page

5
0%
5 min read
Remaining
5 minleft

Click any section to jump — progress syncs automatically

reactjs

React Lazy Loading – Optimizing Bundle Size

What is Lazy Loading?

By default, React bundles your entire application into one large JavaScript file. As your app grows, this file becomes heavy, leading to slow initial load times. Lazy loading (or code splitting) allows you to break your app into smaller chunks and load them only when the user actually navigates to that part of the application.

Using React.lazy and Suspense

The React.lazy function lets you render a dynamic import as a regular component. It must be rendered inside a <Suspense> component, which allows you to show a fallback UI (like a loading spinner) while the lazy component is being fetched.

React JSXRead-only
1
import React, { Suspense } from 'react';

// 1. Define the lazy component
const HeavyChart = React.lazy(() => import('./HeavyChart'));

function App() {
  return (
    <div>
      <h1>My Dashboard</h1>
      {/* 2. Wrap in Suspense with a fallback */}
      <Suspense fallback={<div>Loading Chart...</div>}>
        <HeavyChart />
      </Suspense>
    </div>
  );
}

Route-Based Code Splitting

The most common place to implement lazy loading is at the route level. This ensures that users only download the code for the page they are currently visiting.

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

const Home = lazy(() => import('./routes/Home'));
const Settings = lazy(() => import('./routes/Settings'));

function App() {
  return (
    <Router>
      <Suspense fallback={<LoadingSpinner />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </Router>
  );
}

When to Use Lazy Loading

  • Routes: Every major page in your app should likely be lazy-loaded.
  • Heavy Libraries: Components that use large libraries like D3.js, Three.js, or complex editors.
  • Modals and Dialogs: Components that only appear after a user interaction (like clicking a 'Help' button).
  • Conditional Content: Sections of a page that are hidden behind tabs or accordions.

Error Boundaries with Lazy Loading

If a network error occurs while fetching a lazy component (e.g., the user loses internet), the app will crash unless you wrap the Suspense block in an Error Boundary. This allows you to show a 'Network Error' UI instead of a blank screen.

Try it yourself

import React, { useState, Suspense, lazy } from 'react';

// Simulate a slow-loading component
const LazyComponent = lazy(() => {
  return new Promise(resolve => {
    setTimeout(() => resolve(import('./ProfileCard')), 2000);
  });
});

// Inline Mock of ProfileCard for demo purposes
const ProfileCard = () => (
  <div style={{ border: '2px solid #007bff', padding: '15px', borderRadius: '8px' }}>
    <h4>Kishore Kumar S</h4>
    <p>Flutter Architect & Engineering Manager</p>
  </div>
);

export default function LazyDemo() {
  const [show, setShow] = useState(false);

  return (
    <div style={{ padding: '20px' }}>
      <h3>Lazy Loading Demo</h3>
      <button onClick={() => setShow(true)} disabled={show}>
        {show ? 'Loaded' : 'Load Profile (2s Delay)'}
      </button>
      
      <div style={{ marginTop: '20px' }}>
        {show && (
          <Suspense fallback={<p>⏳ Downloading component chunk...</p>}>
             <ProfileCard />
          </Suspense>
        )}
      </div>
    </div>
  );
}

Test Your Knowledge

Q1
of 3

Which component is required to wrap a React.lazy component?

A
<ErrorBoundary />
B
<Loading />
C
<Suspense />
D
<Provider />
Q2
of 3

What prop does the Suspense component require to show a loading state?

A
loading
B
placeholder
C
fallback
D
spinner
Q3
of 3

What is the primary benefit of code splitting?

A
Makes the code harder to steal
B
Reduces the initial load time of the application
C
Eliminates the need for CSS
D
Automatically fixes syntax errors

Frequently Asked Questions

Can I lazy load named exports?

React.lazy currently only supports default exports. If the module you want to import uses named exports, you must create an intermediate module that re-exports it as a default.

Does lazy loading affect SEO?

Modern search engine crawlers can handle JavaScript and wait for lazy content, but for critical content, Server-Side Rendering (SSR) with frameworks like Next.js is generally preferred.

What is 'Preloading'?

Preloading is a technique where you start loading a lazy component slightly before it's needed (e.g., when a user hovers over a link) to make the transition feel instant.

Previous

react code splitting

Next

react testing

Related Content

Need help?

Explore our comprehensive docs or start a chat with our tech experts.