Course contentsShow
← React
Lesson 1397 of 2,39635. Code SplittingFree lesson

React Router Route Component Splitting

Implementing lazy routes in React Router using lazy imports in route definitions and handling the loading experience.

React Router Route Component Splitting

What you'll learn: How to implement lazy loading in React Router route definitions to automatically split your app by page.

The Core Idea

You've already learned how to lazy-load components with React.lazy() and wrap them in Suspense. Now we bring that pattern directly into your React Router configuration. Instead of importing route components at the top of your file (which bundles them all together), you use React.lazy() right in your route definitions. Each route becomes its own chunk, loaded only when the user navigates to it.

How It Works

When you define routes, replace eager imports with lazy ones:

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

// Lazy-loaded route components
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
const Dashboard = lazy(() => import('./pages/Dashboard'));

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

Notice the Suspense boundary wraps the entire Routes component. When a user clicks a link, React Router starts rendering the new route's component, which suspends while its code loads, triggering your fallback UI.

Handling the Loading Experience

You control what users see during navigation with the fallback prop. Common patterns include full-page spinners or skeleton screens that match your layout. Place the boundary strategically—wrapping Routes gives you one unified loading experience across all route transitions.

Key Takeaway: Combine React.lazy() with React Router's route definitions and wrap your Routes in Suspense to automatically split your app by page, showing fallback UI during navigation.