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.
Level up your Claude Code workflow
50 battle-tested prompt templates you can copy-paste into Claude Code right now.
Free PDF: Claude Code Cheatsheet in 5 Minutes
Key commands, shortcuts, and prompt examples on a single printable page.
About the Author
Masa
Engineer obsessed with Claude Code. Runs claudecode-lab.com, a 10-language tech media with 2,000+ pages.
Related Posts
Creating Custom Slash Commands in Claude Code — Tailor Your Workflow
Learn how to create custom slash commands in Claude Code. Covers file placement, arguments, and automating frequent tasks with practical code examples.
10 Tips to Triple Your Productivity with Claude Code
Learn about 10 tips to triple your productivity using Claude Code. Practical tips and code examples included.
Canvas/WebGL Optimization with Claude Code
Learn about Canvas/WebGL optimization using Claude Code. Practical tips and code examples included.