Optimizing Code Splitting and Lazy Loading with Claude Code
Learn about optimizing code splitting and lazy loading using Claude Code. Practical tips and code examples included.
Why You Need Code Splitting
As SPA bundle sizes grow, initial load times get worse. Properly implemented code splitting and lazy loading let you load only the code you need, exactly when you need it. Claude Code makes it efficient to retrofit this into existing projects.
React.lazy and Suspense
import { lazy, Suspense } from "react";
// Lazy-loaded components
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Settings = lazy(() => import("./pages/Settings"));
const Analytics = lazy(() => import("./pages/Analytics"));
function LoadingSpinner() {
return (
<div className="flex items-center justify-center h-64">
<div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-500" />
</div>
);
}
function App() {
return (
<Suspense fallback={<LoadingSpinner />}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
<Route path="/analytics" element={<Analytics />} />
</Routes>
</Suspense>
);
}
Lazy Loading Named Exports
// Lazy loading a named export
const Chart = lazy(() =>
import("./components/Chart").then((module) => ({
default: module.BarChart,
}))
);
// Generic helper
function lazyNamed<T extends Record<string, any>>(
factory: () => Promise<T>,
name: keyof T
) {
return lazy(() =>
factory().then((module) => ({ default: module[name] }))
);
}
const PieChart = lazyNamed(
() => import("./components/Chart"),
"PieChart"
);
Next.js Dynamic Imports
import dynamic from "next/dynamic";
// Client-side only
const RichEditor = dynamic(() => import("./components/RichEditor"), {
ssr: false,
loading: () => <p>Loading editor...</p>,
});
// Conditional loading
const AdminPanel = dynamic(() => import("./components/AdminPanel"), {
ssr: false,
});
function Page({ isAdmin }: { isAdmin: boolean }) {
return (
<div>
<h1>Main content</h1>
{isAdmin && <AdminPanel />}
</div>
);
}
Route-Based Splitting
import { lazy, Suspense } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";
// Split per route
const routes = [
{ path: "/", component: lazy(() => import("./pages/Home")) },
{ path: "/about", component: lazy(() => import("./pages/About")) },
{ path: "/blog/*", component: lazy(() => import("./pages/Blog")) },
{
path: "/admin/*",
component: lazy(() => import("./pages/Admin")),
},
];
function AppRouter() {
return (
<BrowserRouter>
<Suspense fallback={<LoadingSpinner />}>
<Routes>
{routes.map(({ path, component: Component }) => (
<Route key={path} path={path} element={<Component />} />
))}
</Routes>
</Suspense>
</BrowserRouter>
);
}
Prefetching Strategy
// Prefetch on hover
function PrefetchLink({
to,
factory,
children,
}: {
to: string;
factory: () => Promise<any>;
children: React.ReactNode;
}) {
const handleMouseEnter = () => {
factory(); // Start prefetching
};
return (
<Link to={to} onMouseEnter={handleMouseEnter}>
{children}
</Link>
);
}
// Prefetch a route
const dashboardFactory = () => import("./pages/Dashboard");
const DashboardPage = lazy(dashboardFactory);
// Use in navigation
<PrefetchLink to="/dashboard" factory={dashboardFactory}>
Dashboard
</PrefetchLink>
Bundle Analysis
// webpack-bundle-analyzer configuration
// next.config.js
const withBundleAnalyzer = require("@next/bundle-analyzer")({
enabled: process.env.ANALYZE === "true",
});
module.exports = withBundleAnalyzer({
// Next.js config
});
# Run bundle analysis
ANALYZE=true npm run build
Leveraging Claude Code
Here’s a prompt for asking Claude Code to introduce code splitting. For a broader approach to performance improvements, see the SSR vs SSG comparison, and for development speed, see 10 productivity tips that 3x your output.
Optimize the bundle size.
- Introduce route-based code splitting
- Lazy-load heavy libraries (chart.js, moment, etc.)
- Unify loading states with Suspense
- Analyze the bundle and produce an improvement report
For details on code splitting, see the official React docs. For how to use Claude Code, check the official documentation.
Summary
Code splitting is a performance optimization that has a direct impact on user experience. If you ask Claude Code to handle bundle analysis and implementation as one connected task, it can find effective split points and optimize them.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Just enter your email and we'll send you the single-page A4 cheatsheet right away.
We handle your data with care and never send spam.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
7 CLAUDE.md Templates for Claude Code You Can Copy Into Real Projects
Copy-paste 7 practical CLAUDE.md templates for solo apps, content sites, APIs, teams, and legacy codebases, plus the failure cases to avoid.
Claude Code Approval and Sandbox Guide | Safe Daily Settings for Real Work
Learn how to split Claude Code actions into allow, ask, deny, and sandboxed workflows with working settings, hooks, and rollout examples.
Complete Beginner's Guide to Claude Code 2026 | 7 Steps from Zero to Production-Ready
A complete beginner's guide for first-time Claude Code users. From installation to integrating it into your real development workflow — covering every pitfall Masa ran into when starting out.
Related Products
50 Battle-Tested Claude Code Prompt Templates
Copy, paste, ship. 50 production-ready prompts.
Use proven prompts for code review, refactoring, testing, documentation, debugging, architecture, and incident response.
The Complete Claude Code Setup & Configuration Guide
From install to team-ready workflow.
A practical guide to installation, CLAUDE.md, hooks, MCP servers, permissions, IDE setup, and CI/CD workflows.