JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsperformance
Next
performance
mid
bundling

How does code splitting work and when should you use it?

code-splitting
lazy-loading
webpack
chunks
bundling
Quick Answer

Code splitting breaks your bundle into smaller chunks that load on demand. Use it for route-based splitting, heavy components, and vendor libraries. This reduces initial load time by only loading code when it's needed.

Detailed Explanation

Code Splitting Methods:

  1. Route-based splitting:

    • Each page/route is a separate chunk
    • Most impactful for large apps
    • Easy to implement
  2. Component-based splitting:

    • Heavy components load on demand
    • Modals, charts, editors
    • User interaction triggers load
  3. Vendor splitting:

    • Separate third-party code
    • Changes less often (better caching)
    • Common chunks shared

When to Split:

  • Large components rarely used
  • Features behind user interaction
  • Admin/auth-only sections
  • Heavy libraries

Code Examples

Route-based code splitting
// React Router with lazy loading
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

// Each route is a separate chunk
const Home = lazy(() => import('./pages/Home'));
const Products = lazy(() => import('./pages/Products'));
const ProductDetail = lazy(() => import('./pages/ProductDetail'));
const Admin = lazy(() => import('./pages/Admin'));
const Settings = lazy(() => import('./pages/Settings'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<PageSkeleton />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/products" element={<Products />} />
          <Route path="/products/:id" element={<ProductDetail />} />
          <Route path="/admin/*" element={<Admin />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

// Named chunks for better debugging
const Analytics = lazy(() => 
  import(/* webpackChunkName: "analytics" */ './pages/Analytics')
);

Resources

Webpack Code Splitting

docs

React Code Splitting

docs

Related Questions

How do you analyze and reduce bundle size?

mid
bundling
Next
How do you analyze and reduce bundle size?