Back to Pathway
patternsadvanced

Code Splitting

Code splitting splits the application bundle into smaller chunks loaded on demand using React.lazy and dynamic imports.

Mental Model

"The Just-In-Time Supply Chain: Instead of delivering 50 tons of brick on day 1, trucks deliver roof tiles only when the roof is ready."

Interactive Engine Simulation

Simulation Engine Idle
Click "Execute Code" to run state reconciliation simulation.

Executable Code Snippet

Component.jsx
JSX / React 19
1// Load component only when needed
2const HeavyProfile = React.lazy(() => import('./Profile'));
3
4function App() {
5  return (
6    <Suspense fallback={<Spinner />}>
7      <HeavyProfile />
8    </Suspense>
9  );
10}
Technical Takeaways & Best Practices
  • 01.Component re-renders are triggered by state or prop changes.
  • 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
  • 03.Automatic batching optimizes multiple state updates into a single render cycle.

01. Chunking the Universe

By default, your bundler (Vite/Webpack) creates one giant JS file. `React.lazy` allows you to split this into smaller "chunks." The browser only downloads the code for the current page, which makes the initial load significantly faster, especially on mobile.

Bundle Topography

Main.js (Core)
Admin.js (Deferred)
Charts.js (Deferred)

02. Dynamic Imports

Lazy loading uses the ES6 `import()` syntax, which returns a Promise. React handles the resolving of this Promise and ensures that the component is ready before trying to render it. This is why `Suspense` is required—to tell React what to show while the file is downloading.

Senior Insight

"A great strategy is **Route-based splitting**. Every page in your app should be its own chunk. This ensures the user never downloads the code for the 'Settings' page if they only ever visit 'Home'."