REACT Lesson 23 – Code Splitting | Dataplexa
LESSON 23

Code Splitting

Split your React bundles into smaller chunks that load when needed, reducing initial page load time and improving user experience.

Code splitting is like having a restaurant menu that only shows appetizers first. Customers see something immediately, then get the full menu when they're ready. React works the same way. Your DataFlow dashboard currently loads everything at once. Every chart, every table, every component downloads before users see anything. But what if someone only needs the stats bar? They're waiting for chart libraries they won't even use.

Why Bundle Size Matters

Bundle size directly impacts user experience. A 2MB JavaScript file takes 6 seconds to download on 3G. That's 6 seconds of blank screen while users wonder if your app is broken. Netflix faced this exact problem. Their dashboard loaded slowly because every feature was bundled together. They switched to code splitting and reduced initial load time by 70%. Here's what happens without code splitting:
// DataFlow loads everything upfront
import Header from './Header';
import Sidebar from './Sidebar';
import StatsBar from './StatsBar';
import ChartSection from './ChartSection';
import DataTable from './DataTable';
import FilterBar from './FilterBar';

function DataFlow() {
  return (
    <div>
      <Header />
      <Sidebar />
      <StatsBar />
      <ChartSection />
      <DataTable />
      <FilterBar />
    </div>
  );
}
DataFlow Dashboard - Heavy Bundle
What just happened?
The browser downloaded everything before showing anything. Even though users only see stats first, they waited for charts and tables to download too. Try refreshing - notice the loading delay shows bundle size.

Dynamic Imports

React's React.lazy() function splits code automatically. Instead of importing components normally, you tell React "load this when needed." Think of it like ordering room service. You don't get all meals at check-in. You call when hungry, then food arrives.
// Split heavy chart component
import React, { Suspense, useState } from 'react';

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

function DataFlow() {
  const [showCharts, setShowCharts] = useState(false);
  
  return (
    <div>
      <div>Revenue: $84,230 | Users: 12,847</div>
      <button onClick={() => setShowCharts(true)}>
        Load Charts
      </button>
      {showCharts && (
        <Suspense fallback={<div>Loading charts...</div>}>
          <ChartSection />
        </Suspense>
      )}
    </div>
  );
}
DataFlow Dashboard - Code Split
What just happened?
The dashboard loaded instantly with stats. When you clicked "Load Charts", React downloaded the chart component separately. Users see value immediately, then get advanced features on demand. Try this: click the button and watch the loading state.

Route-Based Splitting

The most common code splitting pattern happens at the route level. Each page becomes its own bundle. Users navigating to the reports page don't download the settings page code. React Router makes this pattern simple:
// DataFlow with route-based code splitting
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import { Suspense } from 'react';

const Dashboard = React.lazy(() => import('./Dashboard'));
const Reports = React.lazy(() => import('./Reports'));
const Settings = React.lazy(() => import('./Settings'));

function DataFlow() {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading page...</div>}>
        <Routes>
          <Route path="/" element={<Dashboard />} />
          <Route path="/reports" element={<Reports />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}
DataFlow - Route Splitting
What just happened?
Each page loads its own bundle when clicked. Dashboard is lightweight (240KB), Reports includes heavy chart libraries (890KB), Settings is minimal (120KB). Users only download what they need. Try switching pages - notice the loading states and bundle sizes.

Bundle Analysis

You can't optimize what you can't measure. Bundle analyzers show exactly what's in your JavaScript files. They reveal which libraries are huge and which components could be split. Webpack Bundle Analyzer creates interactive treemaps of your bundles. Large rectangles mean heavy files. Here's how the DataFlow team uses it:
Before Splitting
main.js: 2.4MB
Contains everything
5s load on 3G
After Splitting
main.js: 340KB
charts.js: 890KB
1.2s initial load
The chart library was 60% of the bundle. By splitting it, initial load time dropped from 5 seconds to 1.2 seconds. Users see the dashboard while chart code downloads in background.

Preloading Strategies

Code splitting doesn't mean waiting. Smart apps preload bundles before users need them. When someone hovers over "Reports" in navigation, start downloading the reports bundle. By the time they click, it's ready.
// Preload on hover for instant navigation
function Navigation() {
  const preloadReports = () => {
    // Start downloading reports bundle
    import('./Reports');
  };
  
  return (
    <nav>
      <Link to="/dashboard">Dashboard</Link>
      <Link 
        to="/reports" 
        onMouseEnter={preloadReports}
      >
        Reports
      </Link>
    </nav>
  );
}
DataFlow - Smart Preloading
What just happened?
Hover over the Reports button and watch the preload status. The bundle downloads before you click. When you actually navigate, the page loads instantly because code is already cached. Try this: hover Reports, wait for "ready", then click.

When NOT to Code Split

Code splitting isn't always better. Small components (under 30KB) aren't worth splitting. The network request overhead outweighs the benefit. Also avoid splitting critical above-the-fold content users need immediately. Airbnb learned this the hard way. They split their search component, causing a loading spinner on the homepage. Users couldn't search for 800ms. They moved search back into the main bundle.
Code Splitting Guidelines
Split routes and large features (500KB+). Keep critical components in main bundle. Split third-party libraries separately. Use preloading for predictable user flows.
Bundle splitting works best for distinct user journeys. Dashboard users might never visit settings. Report viewers rarely need chart editing tools. Split by user intent, not just file size.

Quiz

1. The DataFlow dashboard takes 8 seconds to load because all components download at once. What is the primary benefit of implementing code splitting?


2. Your DataFlow charts component is 890KB and should only load when users click "View Charts". Which React pattern implements this correctly?


3. Users complain that clicking between DataFlow pages shows a loading spinner. What preloading strategy provides instant navigation?


Up Next: Error Boundaries
Handle JavaScript errors gracefully in React applications without crashing the entire user interface.