Skip to main content
XenonStack

Enterprise Digital Platform

XenonStack Insights Code Splitting in React: Lazy, Suspense and Routes

| Published | Updated

Code Splitting in React: Lazy, Suspense and Routes
6:26
Code splitting in React: route and component splitting, React.lazy dynamic imports, Suspense fallbacks, faster startup

Key takeaway

  • Code splitting in React loads only the JavaScript a screen needs. See how dynamic import, React.lazy, Suspense and route splitting work, and the pitfalls.

Code splitting in React means dividing your JavaScript into several bundles so a screen loads only the code it needs, with the rest fetched on demand or in parallel. In React the usual tools are dynamic import(), React.lazy and Suspense, applied at the route or component level.

This guide is for front-end developers and engineering leads whose React bundle has grown slow to start. It explains why splitting helps, the three approaches bundlers support, how lazy and Suspense fit together, the mistakes to avoid, and where AI agents help. It pairs with our notes on performance monitoring tools and management for measuring the result.

What is code splitting?

The webpack guide on code splitting calls it one of the most compelling features of webpack and says it lets you split code into various bundles that can be loaded on demand or in parallel. Without it, a single bundle carries every page and library, and the browser must download and run all of it before the first screen is useful.

Why does code splitting matter for performance?

The web.dev article on code splitting explains that splitting seeks to minimise startup time: less script to parse, compile and execute means the page becomes usable sooner. It also notes that Lighthouse flags pages where executing all the JavaScript takes too long. Splitting does not reduce what the whole app contains. It changes when each part is paid for.

What are the main ways to split code?

The webpack guide lists three general approaches. React apps normally combine the third with their framework or router.

ApproachWhat it doesWatch out for
Entry pointsSplits code manually through the entry configurationThe guide calls it the easiest way but also manual, and duplicated modules end up in every entry bundle
Preventing duplicationUses entry dependencies or SplitChunksPlugin to extract shared dependencies into their own chunkShared code is only extracted into a separate chunk if it meets the size thresholds
Dynamic importsSplits code through inline import() calls inside modulesImports become asynchronous, so loading and error states need handling

How do React.lazy and Suspense work together?

The React lazy reference says lazy lets you defer loading a component's code until it is rendered for the first time. You pass it a function that returns a Promise from a dynamic import, and React does not call that function until the component first renders. Suspense then shows a fallback while the code loads.

Two-column diagram. One bundle: all routes together, heavy libraries, parse and run cost, slow first screen. Split bundles: route chunks, lazy components, Suspense fallback, faster startup.
const Settings = lazy(() => import('./Settings.js'));

<Suspense fallback={<Loading />}>
  <Settings />
</Suspense>

The reference lists the caveats that cause most bugs: declare lazy components at the top level of a module, because declaring them inside another component resets state on re-render; the imported module must use a default export; and a rejected load is thrown to the nearest error boundary, so add one.

Should you split by route or by component?

LevelGood forExample
RoutePages a user may never visit in a sessionLoad the settings page only when the user opens it
ComponentHeavy features that appear after an actionLoad a chart or editor when the user clicks to open it
LibraryA large dependency used in one placeImport it inside the function that needs it

The web.dev article presents route and component splitting as the simpler approach for client-side frameworks, and the React team's post on retiring Create React App points to the lazy option in React Router for route-level splitting. Older tutorials use the react-loadable package and the Switch component from React Router version 5; treat those examples as dated and follow your current router and React documentation instead.

What mistakes should you avoid?

MistakeEffectFix
Splitting everything into tiny chunksMany small requests and flickering fallbacksSplit at route level first, then only heavy components
Declaring lazy inside a componentState is reset on every re-renderMove the lazy call to module level
No fallback or error boundaryBlank screen or a crash when a chunk fails to loadWrap lazy parts in Suspense and an error boundary
Fallback replacing content already shownPage flashes back to a spinner on navigationMark the update as a transition so React keeps the current screen, as the Suspense docs describe

How do AI agents change code splitting?

Bundle analysis is repetitive work that agents can help with. An agent can read a build report, list the largest chunks on each route, compare them with the previous release, and raise a pull request or ticket for a developer to review. Engineers still decide where a boundary belongs and what the loading state should show. Teams building such automation can use ElixirClaw, the AI agents computing platform.

What should you do first?

  1. Build the app and list the largest chunks per route.
  2. Move the least-visited routes behind lazy imports.
  3. Wrap each lazy boundary in Suspense with a light fallback and add an error boundary.
  4. Measure startup again with your monitoring tools and keep only splits that help.
  5. Revisit heavy components and libraries once routes are done.

Related reading: functional programming in Scala, functional programming, Golang vs Rust and functional testing and its types.

To map one decision your agents make, and the data and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What is code splitting in React?

It is dividing your JavaScript into several bundles so a screen loads only the code it needs and the rest is fetched on demand or in parallel.

What does React.lazy do?

It defers loading a component's code until the component is rendered for the first time, using a function that returns a dynamic import.

Why do I need Suspense with React.lazy?

Rendering a lazy component suspends while its code loads, and Suspense displays a fallback such as a spinner or skeleton in the meantime.

Should I split by route or by component?

Start with routes, because users often never visit some pages. Split individual components only when they are heavy and appear after an action.

Does code splitting reduce the size of my app?

No. It changes when parts of the code are downloaded and run, so less is processed at startup.

Ready to put AI agents to work? See an ElixirClaw demo: the agentic OS to build, orchestrate and govern AI agents across your enterprise systems.

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in solving your challenges with the XenonStack team?
Get Started

Tell us about you and your priorities so we can prepare the right conversation. It takes about 2 minutes.

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Continue