JavaScript and React course · Module 8: Advanced React Patterns

Code splitting

10 min read ·
In this lesson14

As our cosmic React application grows, the JavaScript file that loads in the browser also gets bigger. This can lead to longer page load times, higher memory usage, and generally worse performance. Code splitting is a technique that allows you to "split" the application into smaller parts that can be loaded dynamically, only when they are needed.

What is code splitting?

Code splitting is a technique that divides a large JavaScript bundle into smaller chunks that can be loaded on demand or in parallel. Instead of sending the entire application to the user at once, we send only what is needed for the initial render, and the rest is loaded in the background or when needed.

It is like launching a space mission - we don't send all the resources at once, but in stages: first the main ship, then additional modules, and finally smaller tools and equipment when they become needed.

Why do we need code splitting?

Imagine we are creating a space application with many modules:

  • Mission control panel
  • Astronaut monitoring system
  • Galaxy map
  • Discovered planets encyclopedia
  • Flight simulator
  • Interstellar communication center

If we build the entire application as a single bundle, the user must download all that code even if they just want to check the galaxy map. As a result:

  • Longer first page load time
  • Higher browser memory usage
  • Higher data transfer costs (especially important on mobile devices)
  • Unnecessary loading and parsing of code that is not used

Benefits of code splitting

  • Faster initial load - shorter time to interactivity (TTI - Time To Interactive)
  • Better performance on mobile devices - lower memory and CPU usage
  • Critical path prioritization - the most important parts of the application load first
  • Better caching - smaller parts are easier to cache and update
  • Better user experience - the application becomes responsive faster

Implementing code splitting in React

React supports code splitting through dynamic imports and the React.lazy component. Let's see how it works:

1. Dynamic import

The import() function is a standard ES function that allows dynamically importing modules. Instead of loading all dependencies at the top of the file, we can load them only when they are needed:

// Without code splitting
import { calculateOrbit } from './complexOrbitCalculations';

function OrbitCalculator({ planetData }) {
  const orbitInfo = calculateOrbit(planetData);
  return <div>{/* Rendering results */}</div>;
}

// With code splitting
function OrbitCalculator({ planetData }) {
  const [orbitInfo, setOrbitInfo] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Dynamic module import only when the component mounts
    import('./complexOrbitCalculations')
      .then(module => {
        const result = module.calculateOrbit(planetData);
        setOrbitInfo(result);
        setLoading(false);
      });
  }, [planetData]);

  if (loading) return <p>Calculating orbit...</p>;
  return <div>{/* Rendering results */}</div>;
}

2. React.lazy

React.lazy is a function that allows rendering a dynamic import as a regular component. It only works with default exports.

import React, { Suspense } from 'react';

// Regular import
// import GalaxyMap from './GalaxyMap';

// Lazy import
const GalaxyMap = React.lazy(() => import('./GalaxyMap'));
const PlanetDetails = React.lazy(() => import('./PlanetDetails'));
const SpaceshipControls = React.lazy(() => import('./SpaceshipControls'));

function SpaceExplorer() {
  const [view, setView] = useState('map');

  return (
    <div className="space-explorer">
      <nav>
        <button onClick={() => setView('map')}>Galaxy Map</button>
        <button onClick={() => setView('planets')}>Planet Details</button>
        <button onClick={() => setView('controls')}>Control Panel</button>
      </nav>

      <Suspense fallback={<div>Loading module...</div>}>
        {view === 'map' && <GalaxyMap />}
        {view === 'planets' && <PlanetDetails />}
        {view === 'controls' && <SpaceshipControls />}
      </Suspense>
    </div>
  );
}

In the above example:

  1. We use React.lazy to dynamically import components
  2. We wrap components in Suspense to show a fallback while loading
  3. Components are loaded only when they are needed (when the user changes the view)

Suspense

Suspense is a React component that allows "suspending" rendering until certain conditions are met (e.g., data is loaded or component code is available).

Suspense accepts a fallback prop, which is rendered while waiting:

<Suspense fallback={<LoadingSpinner message="Preparing module..." />}>
  <LazilyLoadedComponent />
</Suspense>

Suspense can handle multiple Lazy components at once:

<Suspense fallback={<LoadingSpinner />}>
  <LazyComponent1 />
  <div>
    <LazyComponent2 />
  </div>
  <LazyComponent3 />
</Suspense>

Nesting Suspense

We can also nest Suspense components to achieve more granular control over what is displayed during loading:

function SpaceStation() {
  return (
    <div>
      <h1>Space Station Alpha</h1>

      {/* Main layout loads immediately */}
      <StationLayout />

      {/* Map loads with its own fallback */}
      <Suspense fallback={<p>Loading station map...</p>}>
        <StationMap />
      </Suspense>

      {/* Control panel has nested lazy components */}
      <Suspense fallback={<p>Preparing control panel...</p>}>
        <ControlPanel>
          <Suspense fallback={<p>Loading life support systems...</p>}>
            <LifeSupportMonitor />
          </Suspense>

          <Suspense fallback={<p>Loading engine controls...</p>}>
            <EngineControls />
          </Suspense>
        </ControlPanel>
      </Suspense>
    </div>
  );
}

Route-based code splitting

One of the most common ways to apply code splitting is dividing code based on routes. Each page or view becomes a separate code chunk:

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Navbar from './Navbar';
import LoadingPage from './LoadingPage';

// Lazy loading pages
const MissionControl = lazy(() => import('./pages/MissionControl'));
const GalaxyMap = lazy(() => import('./pages/GalaxyMap'));
const CrewManagement = lazy(() => import('./pages/CrewManagement'));
const ResearchDatabase = lazy(() => import('./pages/ResearchDatabase'));
const SpaceshipConfig = lazy(() => import('./pages/SpaceshipConfig'));

function App() {
  return (
    <Router>
      <Navbar />
      <Suspense fallback={<LoadingPage />}>
        <Switch>
          <Route exact path="/" component={MissionControl} />
          <Route path="/galaxy-map" component={GalaxyMap} />
          <Route path="/crew" component={CrewManagement} />
          <Route path="/research" component={ResearchDatabase} />
          <Route path="/spaceship" component={SpaceshipConfig} />
        </Switch>
      </Suspense>
    </Router>
  );
}

Library code splitting

We can also apply code splitting for large libraries that are not needed immediately:

import React, { useState } from 'react';

function DataVisualizer({ data }) {
  const [charts, setCharts] = useState(null);
  const [showCharts, setShowCharts] = useState(false);

  const loadChartsLibrary = async () => {
    // Load the library only when the user wants to see charts
    const D3Module = await import('d3');
    const ChartModule = await import('./ChartComponent');

    setCharts({
      d3: D3Module.default,
      ChartComponent: ChartModule.default
    });
  };

  const handleShowCharts = () => {
    if (!charts) {
      setShowCharts(true);
      loadChartsLibrary();
    } else {
      setShowCharts(true);
    }
  };

  return (
    <div className="data-visualizer">
      <h2>Space Exploration Data</h2>
      <button onClick={handleShowCharts}>
        {showCharts ? 'Hide charts' : 'Show charts'}
      </button>

      {showCharts && (
        <>
          {charts ? (
            <charts.ChartComponent data={data} d3={charts.d3} />
          ) : (
            <p>Loading advanced charts...</p>
          )}
        </>
      )}
    </div>
  );
}

Preloading

Sometimes we know that a component will be needed soon (e.g., when the user hovers over a button that will show a modal). We can start loading the module earlier:

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

function PlanetInfoButton({ planetId }) {
  const [showExplorer, setShowExplorer] = useState(false);

  const handleMouseEnter = () => {
    // Start downloading the module when the user hovers over the button
    const PlanetExplorerModule = import('./PlanetExplorer');
  };

  return (
    <>
      <button
        onMouseEnter={handleMouseEnter}
        onClick={() => setShowExplorer(true)}
      >
        Explore planet {planetId}
      </button>

      {showExplorer && (
        <Suspense fallback={<p>Preparing explorer...</p>}>
          <PlanetExplorer planetId={planetId} />
        </Suspense>
      )}
    </>
  );
}

Named exports and code splitting

React.lazy only works with default exports. If we want to use named exports, we need to create an intermediate module:

// MathUtils.js
export const calculateDistance = (a, b) => { /* ... */ };
export const calculateVelocity = (distance, time) => { /* ... */ };
export const calculateAcceleration = (velocity, time) => { /* ... */ };

// DistanceCalculator.js (intermediate module)
export { calculateDistance } from './MathUtils';
export default calculateDistance;

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

Alternatively, we can manually handle the import and extract the desired export:

const calculateVelocity = React.lazy(() =>
  import('./MathUtils').then(module => ({ default: module.calculateVelocity }))
);

Code splitting strategies

1. Route-based splitting

The most common and easiest approach - each page is a separate code chunk.

2. Feature-based splitting

Components related to a specific functionality (e.g., admin panel, advanced analytics) are grouped together.

// Loading the entire admin module on demand
const AdminDashboard = React.lazy(() => import('./admin/Dashboard'));

function App() {
  const [isAdmin, setIsAdmin] = useState(false);

  // isAdmin is set after user login

  return (
    <div>
      {isAdmin ? (
        <Suspense fallback={<p>Loading admin panel...</p>}>
          <AdminDashboard />
        </Suspense>
      ) : (
        <UserDashboard />
      )}
    </div>
  );
}

3. Priority-based splitting

Critical components loaded immediately, less important ones lazily.

// Critical components imported normally
import CriticalSystemStatus from './CriticalSystemStatus';
import NavigationControls from './NavigationControls';

// Less important components loaded lazily
const SystemLogs = React.lazy(() => import('./SystemLogs'));
const CrewSchedule = React.lazy(() => import('./CrewSchedule'));
const MaintenanceStatus = React.lazy(() => import('./MaintenanceStatus'));

function SpaceshipDashboard() {
  return (
    <div className="dashboard">
      <div className="critical-section">
        <CriticalSystemStatus />
        <NavigationControls />
      </div>

      <Suspense fallback={<p>Loading additional modules...</p>}>
        <div className="secondary-section">
          <SystemLogs />
          <CrewSchedule />
          <MaintenanceStatus />
        </div>
      </Suspense>
    </div>
  );
}

4. Vendor splitting

Splitting large external libraries into separate chunks.

In webpack, this can be achieved using the splitChunks configuration:

module.exports = {
  //...
  optimization: {
    splitChunks: {
      chunks: 'all',
      maxInitialRequests: Infinity,
      minSize: 0,
      cacheGroups: {
        vendor: {
          test: /[\/]node_modules[\/]/,
          name(module) {
            // get the name. E.g. node_modules/packageName/sub/path
            // or node_modules/packageName
            const packageName = module.context.match(
              /[\/]node_modules[\/](.*?)([\/]|$)/
            )[1];

            // npm package names are URL-safe, but some servers don't like @ symbols
            return `npm.${packageName.replace('@', '')}`;
          },
        },
      },
    },
  },
};

Analyzing and debugging code splitting

Analyzing bundle sizes

Tools like "webpack-bundle-analyzer" or "source-map-explorer" help visualize bundle contents and identify splitting opportunities:

# Installation
npm install --save-dev webpack-bundle-analyzer

# Configuration in webpack.config.js
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin()
  ]
}

Debugging code-splitting issues

Common code splitting problems and their solutions:

  1. Components flash during loading

    • Solution: Design the fallback to match the final component layout
  2. Too many small chunks

    • Solution: Group related components in a single dynamic import
  3. SSR (Server-Side Rendering) issues

    • Solution: Use loadable-components instead of React.lazy for SSR

Best practices for code splitting

  1. Don't overdo the splitting - too many small chunks can lead to performance issues due to numerous HTTP requests

  2. Analyze your bundles - regularly monitor the size and contents of bundles

  3. Use Magic Comments in webpack for better control over chunks:

    // Named chunk
    const HomeComponent = React.lazy(() => import(
      /* webpackChunkName: "home" */
      './HomeComponent'
    ));
    
    // Prefetch - suggest to the browser that this resource will be needed
    const SettingsComponent = React.lazy(() => import(
      /* webpackChunkName: "settings" */
      /* webpackPrefetch: true */
      './SettingsComponent'
    ));
    
    // Preload - load this resource with high priority
    const ProfileComponent = React.lazy(() => import(
      /* webpackChunkName: "profile" */
      /* webpackPreload: true */
      './ProfileComponent'
    ));
  4. Use code splitting together with caching - properly configured cache headers for chunks can significantly improve performance

  5. Monitor the impact on performance - use tools like Lighthouse to measure load times and TTI (Time To Interactive)

Code splitting and TypeScript

TypeScript works well with code splitting but requires a few additional steps:

// Make sure tsconfig.json has:
// "module": "esnext"

// Dynamic import with typing
const DataVisualization = React.lazy(() =>
  import('./DataVisualization') as Promise<{ default: React.ComponentType<DataVisProps> }>
);

interface DataVisProps {
  data: Array<DataPoint>;
  width: number;
  height: number;
}

interface DataPoint {
  x: number;
  y: number;
  label: string;
}

function Dashboard() {
  const [data, setData] = useState<Array<DataPoint>>([]);

  return (
    <div>
      <h1>Space Mission Panel</h1>

      <Suspense fallback={<div>Loading visualization...</div>}>
        <DataVisualization
          data={data}
          width={800}
          height={400}
        />
      </Suspense>
    </div>
  );
}

Summary

Code splitting is a powerful optimization technique that allows for significantly improving the performance of React applications, especially for larger projects. Thanks to code splitting, users load only what they need, which leads to faster application startup and a better user experience.

Key tools and methods include:

  • React.lazy() and Suspense for components
  • Dynamic import() for modules
  • Splitting strategies based on routes, functionality, or priority
  • Bundle analysis tools to help with decision making

By implementing code splitting in our cosmic application, we can ensure that users quickly gain access to the most important features, and additional resources are loaded when they are needed - similar to a multi-stage space mission where each module is delivered at the right time.

Code for this lesson: App.jsx
import React, { createContext, useContext, useState } from 'react';

// ============================================
// PATTERN: Compound Components
// ============================================
// Components sharing state through Context

// Context for the Accordion
const AccordionContext = createContext();

function useAccordion() {
  const context = useContext(AccordionContext);
  if (!context) {
    throw new Error('Accordion components must be used within <Accordion>');
  }
  return context;
}

// Main Accordion component
function Accordion({ children, defaultOpen = null }) {
  const [openItem, setOpenItem] = useState(defaultOpen);

  const toggle = (id) => {
    setOpenItem(prev => prev === id ? null : id);
  };

  return (
    <AccordionContext.Provider value={{ openItem, toggle }}>
      <div style={styles.accordion}>
        {children}
      </div>
    </AccordionContext.Provider>
  );
}

// Sub-component: Item
function AccordionItem({ children, id }) {
  const { openItem } = useAccordion();
  const isOpen = openItem === id;

  return (
    <div style={{
      ...styles.item,
      borderColor: isOpen ? '#00d4ff' : 'rgba(255,255,255,0.1)',
    }}>
      {React.Children.map(children, child =>
        React.cloneElement(child, { itemId: id, isOpen })
      )}
    </div>
  );
}

// Sub-component: Header
function AccordionHeader({ children, itemId }) {
  const { openItem, toggle } = useAccordion();
  const isOpen = openItem === itemId;

  return (
    <button
      onClick={() => toggle(itemId)}
      style={styles.header}
    >
      <span>{children}</span>
      <span style={{
        transform: isOpen ? 'rotate(180deg)' : 'rotate(0)',
        transition: 'transform 0.3s ease',
      }}>
        ▼
      </span>
    </button>
  );
}

// Sub-component: Panel
function AccordionPanel({ children, isOpen }) {
  return (
    <div style={{
      ...styles.panel,
      maxHeight: isOpen ? '500px' : '0',
      padding: isOpen ? '20px' : '0 20px',
      opacity: isOpen ? 1 : 0,
    }}>
      {children}
    </div>
  );
}

// We combine components
Accordion.Item = AccordionItem;
Accordion.Header = AccordionHeader;
Accordion.Panel = AccordionPanel;

// ============================================
// PATTERN: Tabs Compound Component
// ============================================

const TabsContext = createContext();

function Tabs({ children, defaultTab }) {
  const [activeTab, setActiveTab] = useState(defaultTab);

  return (
    <TabsContext.Provider value={{ activeTab, setActiveTab }}>
      <div style={styles.tabs}>
        {children}
      </div>
    </TabsContext.Provider>
  );
}

function TabList({ children }) {
  return (
    <div style={styles.tabList}>
      {children}
    </div>
  );
}

function Tab({ children, id }) {
  const { activeTab, setActiveTab } = useContext(TabsContext);
  const isActive = activeTab === id;

  return (
    <button
      onClick={() => setActiveTab(id)}
      style={{
        ...styles.tab,
        background: isActive ? '#00d4ff' : 'transparent',
        color: isActive ? '#000' : '#fff',
      }}
    >
      {children}
    </button>
  );
}

function TabPanels({ children }) {
  return <div>{children}</div>;
}

function TabPanel({ children, id }) {
  const { activeTab } = useContext(TabsContext);

  if (activeTab !== id) return null;

  return (
    <div style={styles.tabPanel}>
      {children}
    </div>
  );
}

Tabs.List = TabList;
Tabs.Tab = Tab;
Tabs.Panels = TabPanels;
Tabs.Panel = TabPanel;

// ============================================
// Demo App
// ============================================

function CompoundComponentsDemo() {
  return (
    <div style={styles.container}>
      <header style={styles.headerSection}>
        <h1 style={styles.title}>Compound Components</h1>
        <p style={styles.subtitle}>
          Design pattern for components sharing state
        </p>
      </header>

      <div style={styles.content}>
        {/* Accordion Demo */}
        <div style={styles.section}>
          <h2 style={styles.sectionTitle}>Accordion</h2>

          <Accordion defaultOpen="item1">
            <Accordion.Item id="item1">
              <Accordion.Header>What are Compound Components?</Accordion.Header>
              <Accordion.Panel>
                <p>
                  Compound Components is a pattern where components share
                  internal state through Context. This allows creating
                  flexible and readable component APIs.
                </p>
              </Accordion.Panel>
            </Accordion.Item>

            <Accordion.Item id="item2">
              <Accordion.Header>Pattern advantages</Accordion.Header>
              <Accordion.Panel>
                <ul style={{ marginLeft: '20px' }}>
                  <li>Readable and declarative syntax</li>
                  <li>Flexibility in component layout</li>
                  <li>Encapsulation of logic in the parent</li>
                  <li>Easy addition of new features</li>
                </ul>
              </Accordion.Panel>
            </Accordion.Item>

            <Accordion.Item id="item3">
              <Accordion.Header>Implementation</Accordion.Header>
              <Accordion.Panel>
                <p>
                  Implementation relies on React Context for sharing
                  state and on static properties for grouping sub-components.
                </p>
              </Accordion.Panel>
            </Accordion.Item>
          </Accordion>
        </div>

        {/* Tabs Demo */}
        <div style={styles.section}>
          <h2 style={styles.sectionTitle}>Tabs</h2>

          <Tabs defaultTab="tab1">
            <Tabs.List>
              <Tabs.Tab id="tab1">Planets</Tabs.Tab>
              <Tabs.Tab id="tab2">Stars</Tabs.Tab>
              <Tabs.Tab id="tab3">Galaxies</Tabs.Tab>
            </Tabs.List>

            <Tabs.Panels>
              <Tabs.Panel id="tab1">
                <h3>Planets of the Solar System</h3>
                <p>Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune</p>
              </Tabs.Panel>
              <Tabs.Panel id="tab2">
                <h3>Star types</h3>
                <p>Stars are classified into dwarfs, giants, supergiants and other spectral types.</p>
              </Tabs.Panel>
              <Tabs.Panel id="tab3">
                <h3>Types of galaxies</h3>
                <p>Spiral, elliptical, irregular, and lenticular galaxies.</p>
              </Tabs.Panel>
            </Tabs.Panels>
          </Tabs>
        </div>
      </div>

      <footer style={styles.footer}>
        <p>Compound Components • Context API • Static Properties</p>
      </footer>
    </div>
  );
}

const styles = {
  container: {
    minHeight: '100vh',
    background: 'linear-gradient(135deg, #1a1a2e 0%, #16213e 100%)',
    padding: '30px',
    fontFamily: "'Segoe UI', sans-serif",
    color: '#fff',
  },
  headerSection: {
    textAlign: 'center',
    marginBottom: '40px',
  },
  title: {
    fontSize: '2.5em',
    color: '#00d4ff',
    marginBottom: '10px',
  },
  subtitle: {
    opacity: 0.7,
  },
  content: {
    maxWidth: '800px',
    margin: '0 auto',
  },
  section: {
    background: 'rgba(255,255,255,0.05)',
    borderRadius: '15px',
    padding: '25px',
    marginBottom: '25px',
    border: '1px solid rgba(255,255,255,0.1)',
  },
  sectionTitle: {
    color: '#ffd700',
    marginBottom: '20px',
  },
  accordion: {
    display: 'flex',
    flexDirection: 'column',
    gap: '10px',
  },
  item: {
    borderRadius: '10px',
    border: '2px solid',
    overflow: 'hidden',
    transition: 'border-color 0.3s ease',
  },
  header: {
    width: '100%',
    padding: '15px 20px',
    background: 'rgba(255,255,255,0.05)',
    border: 'none',
    color: '#fff',
    fontSize: '16px',
    cursor: 'pointer',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  panel: {
    overflow: 'hidden',
    transition: 'all 0.3s ease',
    lineHeight: 1.6,
  },
  tabs: {},
  tabList: {
    display: 'flex',
    gap: '10px',
    marginBottom: '20px',
  },
  tab: {
    padding: '12px 24px',
    border: '2px solid #00d4ff',
    borderRadius: '8px',
    cursor: 'pointer',
    fontWeight: 'bold',
    transition: 'all 0.3s ease',
  },
  tabPanel: {
    padding: '20px',
    background: 'rgba(255,255,255,0.05)',
    borderRadius: '10px',
  },
  footer: {
    textAlign: 'center',
    marginTop: '40px',
    opacity: 0.7,
  },
};

export default CompoundComponentsDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Hands-on tasks in the game

  • Click in order

    Arrange the syntax for React.lazy with dynamic import:

  1. Click in orderReact.lazy and Suspense

Useful articles