Loading

Quipoin Menu

Learn • Practice • Grow

react / Code Splitting and Lazy Loading
tutorial

Code Splitting and Lazy Loading

As your React app grows, the bundle size increases, leading to slower initial load times. **Code splitting** is a technique that allows you to split your code into smaller chunks and load them on demand. **Lazy loading** is the practice of loading these chunks only when they're needed.

What is Code Splitting?

Code splitting is the process of splitting your application's bundle into smaller pieces. Instead of loading the entire app at once, users load only the code required for the current page. Other code loads when needed, improving initial load performance.

Think of code splitting like a restaurant menu. You don't bring the entire kitchen to the table you order what you want, when you want it.

React.lazy() and Suspense

React provides built-in support for code splitting with `React.lazy()` and ``. `React.lazy()` lets you render a dynamic import as a regular component. `` shows a fallback while the component loads.
import React, { Suspense } from 'react';

<!-- Lazy load components -->
const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));
const Contact = React.lazy(() => import('./pages/Contact'));

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

Route-Based Code Splitting

The most common approach is to split by routes each page loads only when the user navigates to it.
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const Settings = React.lazy(() => import('./pages/Settings'));
const Profile = React.lazy(() => import('./pages/Profile'));

Component-Level Code Splitting

You can also lazy load individual components, like a heavy modal or chart that only appears after user interaction.
const HeavyChart = React.lazy(() => import('./components/HeavyChart'));

function Dashboard() {
  const [showChart, setShowChart] = useState(false);

  return (
    <div>
      <button onClick={() => setShowChart(true)}>Show Chart</button>
      {showChart && (
        <Suspense fallback={<div>Loading chart...</div>}>
          <HeavyChart />
        </Suspense>
      )}
    </div>
  );
}

Two Minute Drill

  • Code splitting breaks your bundle into smaller chunks loaded on demand.
  • React.lazy() enables dynamic imports for components.
  • Suspense shows a fallback UI while lazy components load.
  • Route-based splitting is the most common and effective pattern.
  • Code splitting improves initial load time and overall performance.

Need more clarification?

Drop us an email at career@quipoinfotech.com