JavaScript and React course ยท Module 6: React Router

Lazy Loading Components on a Cosmic Journey

7 min read ยท
In this lesson8

During a long intergalactic journey, we don't need to load all the equipment onto the spaceship right away. Similarly in React applications, especially larger ones, we don't need to load all components right away during application initialization. This is where lazy loading comes to our aid.

What is Lazy Loading?

Lazy loading is a performance optimization technique that involves loading components, modules, or resources only when they are actually needed, instead of loading them upfront during application initialization. In React, we accomplish this using the React.lazy() function combined with Suspense.

Basics of Lazy Loading in React

To implement lazy loading of a component, instead of the standard component import:

import HeavyDashboard from './HeavyDashboard';

We use the React.lazy() function with a dynamic import:

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

// Lazy loading of a component
const HeavyDashboard = lazy(() => import('./HeavyDashboard'));

function App() {
  return (
    <div>
      <h1>Flight Control Center</h1>

      {/* Suspense provides a fallback component during loading */}
      <Suspense fallback={<div>Loading control panel...</div>}>
        <HeavyDashboard />
      </Suspense>
    </div>
  );
}

In this example:

  • lazy() accepts a function that must call a dynamic import()
  • Suspense displays a fallback (replacement component) during lazy component loading
  • The actual HeavyDashboard component will only load when it is rendered

Lazy Loading in React Router

In applications using React Router, we can lazily load components for individual routes. This way the initial application bundle will be smaller, and the user will only download code for the parts of the application they visit:

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

// Lazily loaded components
const MissionControl = lazy(() => import('./MissionControl'));
const SpaceshipSettings = lazy(() => import('./SpaceshipSettings'));
const GalacticMap = lazy(() => import('./GalacticMap'));
const CrewQuarters = lazy(() => import('./CrewQuarters'));

// Always loaded component (small and frequently used)
import NavigationBar from './NavigationBar';

function App() {
  return (
    <Router>
      <NavigationBar />

      <Suspense fallback={<div className="loading-screen">Preparing module...</div>}>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/mission-control" element={<MissionControl />} />
          <Route path="/spaceship-settings" element={<SpaceshipSettings />} />
          <Route path="/galactic-map" element={<GalacticMap />} />
          <Route path="/crew-quarters" element={<CrewQuarters />} />
        </Routes>
      </Suspense>
    </Router>
  );
}

In this example, only components for the currently visited route will be loaded. We can also add individual Suspense components for each route if we want different loading indicators:

<Routes>
  <Route path="/" element={<HomePage />} />
  <Route
    path="/mission-control"
    element={
      <Suspense fallback={<div>Initializing mission control panel...</div>}>
        <MissionControl />
      </Suspense>
    }
  />
  <Route
    path="/galactic-map"
    element={
      <Suspense fallback={<div>Loading galactic map...</div>}>
        <GalacticMap />
      </Suspense>
    }
  />
</Routes>

Advanced Lazy Loading Techniques

Prefetching (Pre-loading)

Sometimes we know with high probability that the user will visit a specific route. We can then pre-load the component before the user actually clicks the link:

import { lazy } from 'react';

// Lazy component declaration
const GalacticMap = lazy(() => import('./GalacticMap'));

// Navigation component with prefetching
function NavigationLink({ to, children }) {
  // Function for pre-loading
  const prefetchComponent = () => {
    // Dynamic import as Promise - starts loading
    import('./GalacticMap');
  };

  return (
    <Link
      to={to}
      onMouseOver={prefetchComponent} // Start loading on mouse hover
      onFocus={prefetchComponent}     // For accessibility, loading on focus
    >
      {children}
    </Link>
  );
}

// Usage in a component
function Navigation() {
  return (
    <nav>
      <NavigationLink to="/galactic-map">Galactic Map</NavigationLink>
    </nav>
  );
}

Route Grouping (route-based code splitting)

We can group related lazy-loaded components to reduce the number of separate network requests:

// Grouping cockpit-related components
const CockpitModule = lazy(() => import('./modules/CockpitModule'));

// Using the grouped module in routing
<Route path="/cockpit/*" element={<CockpitModule />} />

// In CockpitModule.js we have internal routes
function CockpitModule() {
  return (
    <Routes>
      <Route path="/" element={<CockpitOverview />} />
      <Route path="/navigation" element={<NavigationControls />} />
      <Route path="/engines" element={<EngineControls />} />
      <Route path="/life-support" element={<LifeSupportSystems />} />
    </Routes>
  );
}

In this approach, all cockpit components will be fetched as one chunk of code when the user enters any /cockpit/* route.

Error Handling During Loading

In space, we must always be prepared for unforeseen situations. In the case of lazy loading, it may happen that the component loading attempt fails (e.g., due to network problems):

import React, { lazy, Suspense } from 'react';
import { ErrorBoundary } from 'react-error-boundary';

const GalacticMap = lazy(() => import('./GalacticMap'));

function ErrorFallback({ error, resetErrorBoundary }) {
  return (
    <div className="error-container">
      <h2>Problem encountered while loading the module</h2>
      <p>Error: {error.message}</p>
      <button onClick={resetErrorBoundary}>
        Try again
      </button>
    </div>
  );
}

function MapSection() {
  return (
    <ErrorBoundary
      FallbackComponent={ErrorFallback}
      onReset={() => {
        // Optional state reset logic
      }}
    >
      <Suspense fallback={<div>Loading galactic map...</div>}>
        <GalacticMap />
      </Suspense>
    </ErrorBoundary>
  );
}

When is Lazy Loading Worth Using?

Lazy loading is especially useful in the following cases:

  1. Large applications with many components, where the user typically only uses a small part of the functionality during one session

  2. Rarely used features - for example, an admin panel that is used only by a few users

  3. Heavy dependencies - components that use large libraries (e.g., text editors, maps, charts)

  4. Alternative user paths - when different users use different parts of the application depending on their role

Best Practices

1. Place Suspense Higher in the Component Tree

Instead of wrapping each lazy-loaded component in a separate Suspense, it's often better to place one Suspense higher in the tree:

function App() {
  return (
    <Suspense fallback={<GlobalLoadingSpinner />}>
      <Router>
        <Routes>
          {/* Lazy-loaded routes */}
        </Routes>
      </Router>
    </Suspense>
  );
}

2. Apply Appropriate Code Splitting Boundaries

Split code along natural application boundaries:

  • Splitting by routes (routing)
  • Splitting by functional modules
  • Splitting between public and private parts of the application

3. Avoid Too-fine Splitting

Too-fine code splitting can lead to many small network requests, which can be less efficient than a few larger ones. Find the golden mean.

4. Always Provide a Good Fallback

Make sure the fallback in Suspense is visually consistent with the rest of the application and gives the user clear information about the loading state.

5. Test on Real Devices and Slow Connections

Lazy loading may work great on fast developer connections, but always test how the user experience looks on slower connections.

Example Implementation

Here's an example of a more extensive space application with lazy loading:

import React, { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ErrorBoundary } from 'react-error-boundary';

// Always loaded components
import MainLayout from './layouts/MainLayout';
import LoadingScreen from './components/LoadingScreen';
import ErrorFallback from './components/ErrorFallback';

// Lazy-loaded pages
const HomePage = lazy(() => import('./pages/HomePage'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const NavigationModule = lazy(() => import('./modules/NavigationModule'));
const LifeSupportModule = lazy(() => import('./modules/LifeSupportModule'));
const CommunicationModule = lazy(() => import('./modules/CommunicationModule'));
const CrewModule = lazy(() => import('./modules/CrewModule'));
const SettingsPage = lazy(() => import('./pages/SettingsPage'));
const NotFoundPage = lazy(() => import('./pages/NotFoundPage'));

function App() {
  return (
    <Router>
      <ErrorBoundary FallbackComponent={ErrorFallback}>
        <MainLayout>
          <Suspense fallback={<LoadingScreen />}>
            <Routes>
              <Route path="/" element={<HomePage />} />
              <Route path="/dashboard" element={<Dashboard />} />

              {/* Nested modules with their own routes */}
              <Route path="/navigation/*" element={<NavigationModule />} />
              <Route path="/life-support/*" element={<LifeSupportModule />} />
              <Route path="/communication/*" element={<CommunicationModule />} />
              <Route path="/crew/*" element={<CrewModule />} />

              <Route path="/settings" element={<SettingsPage />} />
              <Route path="/404" element={<NotFoundPage />} />
              <Route path="*" element={<Navigate to="/404" replace />} />
            </Routes>
          </Suspense>
        </MainLayout>
      </ErrorBoundary>
    </Router>
  );
}

export default App;

Summary

Lazy loading is a powerful React application optimization technique that allows:

  1. Reducing the initial JavaScript bundle size
  2. Shortening application loading time
  3. Improving user experience through faster initial rendering
  4. Loading code only when it's actually needed

It's like smart resource management on a spaceship - instead of taking everything at the beginning of the journey, we transport only what's currently needed, saving fuel and speeding up the launch.

Code for this lesson: App.jsx
import React from 'react';
import { BrowserRouter, Routes, Route, Link, useSearchParams } from 'react-router-dom';

// Product list with filtering
function ProductList() {
  const [searchParams, setSearchParams] = useSearchParams();

  const category = searchParams.get('category') || 'all';
  const sortBy = searchParams.get('sort') || 'name';
  const search = searchParams.get('search') || '';

  const products = [
    { id: 1, name: 'Space suit', category: 'equipment', price: 5000 },
    { id: 2, name: 'Astronaut helmet', category: 'equipment', price: 1500 },
    { id: 3, name: 'Model rocket', category: 'toys', price: 200 },
    { id: 4, name: 'Teleskop', category: 'tools', price: 3000 },
    { id: 5, name: 'Galaxy map', category: 'tools', price: 500 },
    { id: 6, name: 'Astronaut figurine', category: 'toys', price: 50 },
  ];

  // Filtering
  let filteredProducts = products;
  if (category !== 'all') {
    filteredProducts = filteredProducts.filter(p => p.category === category);
  }
  if (search) {
    filteredProducts = filteredProducts.filter(p =>
      p.name.toLowerCase().includes(search.toLowerCase())
    );
  }

  // Sorting
  filteredProducts.sort((a, b) => {
    if (sortBy === 'price') return a.price - b.price;
    return a.name.localeCompare(b.name);
  });

  const updateFilter = (key, value) => {
    const newParams = new URLSearchParams(searchParams);
    if (value) {
      newParams.set(key, value);
    } else {
      newParams.delete(key);
    }
    setSearchParams(newParams);
  };

  return (
    <div className="product-list">
      <h1>Space shop</h1>

      <div className="filters">
        <div className="filter-group">
          <label>Search:</label>
          <input
            type="text"
            value={search}
            onChange={(e) => updateFilter('search', e.target.value)}
            placeholder="Type a name..."
          />
        </div>

        <div className="filter-group">
          <label>Category:</label>
          <select
            value={category}
            onChange={(e) => updateFilter('category', e.target.value)}
          >
            <option value="all">All</option>
            <option value="equipment">Equipment</option>
            <option value="tools">Tools</option>
            <option value="toys">Toys</option>
          </select>
        </div>

        <div className="filter-group">
          <label>Sort:</label>
          <select
            value={sortBy}
            onChange={(e) => updateFilter('sort', e.target.value)}
          >
            <option value="name">Name</option>
            <option value="price">Price</option>
          </select>
        </div>
      </div>

      <div className="current-params">
        <strong>URL params:</strong> {searchParams.toString() || '(none)'}
      </div>

      <div className="products">
        {filteredProducts.map(product => (
          <div key={product.id} className="product">
            <h3>{product.name}</h3>
            <p className="category">{product.category}</p>
            <p className="price">{product.price} credits</p>
          </div>
        ))}
        {filteredProducts.length === 0 && (
          <p className="no-results">No products matching criteria</p>
        )}
      </div>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      <div className="app">
        <nav>
          <Link to="/products">All</Link>
          <Link to="/products?category=equipment">Equipment</Link>
          <Link to="/products?category=tools">Tools</Link>
          <Link to="/products?category=toys&sort=price">Toys (price)</Link>
        </nav>
        <Routes>
          <Route path="/" element={<ProductList />} />
          <Route path="/products" element={<ProductList />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
}

export default App;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the React.lazy() function return in React?

  2. 2. What is the role of the Suspense component with lazy loading?

Hands-on tasks in the game

  • Code editor

    Protected Routes

  • Click in order

    Arrange the Route syntax with a dynamic parameter:

  • Code editor

    Lazy loading components

  • Vertical ordering

    Arrange the steps of lazy loading a component in React:

  1. Coding taskPractice: Protected Routes
  2. Click in orderDynamic parameters in paths
  3. Coding taskPractice: Loading States
  4. QuestionReact.lazy and Suspense
  5. QuestionSuspense fallback
  6. Put in orderLazy loading process in React

Useful articles