SyntaxStudy
Sign Up
React Code Splitting with React.lazy and Suspense
React Beginner 1 min read

Code Splitting with React.lazy and Suspense

Code splitting divides your JavaScript bundle into smaller chunks that are downloaded on demand rather than all at once. React.lazy and Suspense are the built-in mechanism for component-level code splitting. React.lazy accepts a function that returns a dynamic import of a module with a default export. The component is not downloaded until it is first rendered. Suspense provides a fallback UI to display while a lazy component is loading. You can nest Suspense boundaries at different levels of the component tree to provide granular loading states — a spinner for a panel that loads independently, a skeleton for an entire page section. Multiple lazy components inside the same Suspense boundary share the same fallback. Route-based code splitting is the most impactful form: each route imports its page component lazily so users only download the code for pages they actually visit. This dramatically reduces the initial bundle size for large single-page applications.
Example
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';

// ── Lazy route components ──────────────────────────────────────────────────
const Home      = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings  = lazy(() => import('./pages/Settings'));

// ── Route-level code splitting ─────────────────────────────────────────────
function AppRoutes() {
    return (
        <Suspense fallback={<div className="page-spinner">Loading page…</div>}>
            <Routes>
                <Route path="/"          element={<Home />} />
                <Route path="/dashboard" element={<Dashboard />} />
                <Route path="/settings"  element={<Settings />} />
            </Routes>
        </Suspense>
    );
}

// ── Nested Suspense for sub-components ─────────────────────────────────────
const HeavyChart = lazy(() => import('./components/HeavyChart'));

function DashboardPage() {
    return (
        <div>
            <h1>Dashboard</h1>
            {/* Chart has its own dedicated loading state */}
            <Suspense fallback={<div className="chart-skeleton" />}>
                <HeavyChart />
            </Suspense>
        </div>
    );
}

export default AppRoutes;