Code Splitting in React.js
Code splitting, sometimes known as chunking, lazy loading, or dynamic bundling, is an essential React.js development method that lowers the final build size of your application and speeds up load times. Code splitting divides the big application into more manageable, targeted portions that may be loaded asynchronously and on demand, avoiding the need for users to download the complete program at once. This results in a speedier and more seamless user experience since users only download the code required for the particular section of the application they are currently viewing.

With features like the lazy function for dynamic component imports and the Suspense component for displaying a fallback message, such “Loading Component,” while the necessary code loads, React makes code separation easier. Together with bundlers like Webpack, these React capabilities efficiently divide the code into these smaller, named chunks, which can also help with debugging and readability. For large-scale systems, where initial load times can have a substantial impact on user engagement, this optimisation technique is very advantageous.
The Problem Code Splitting Solves
The Code Splitting Issue Is Solved The size of web applications’ JavaScript bundles can increase significantly as they get more complicated. When visiting such an app, users must download the entire bundle before using it. This might cause poor user experience and long initial load times for devices with insufficient memory or slow network connections. Asynchronous code functions are necessary for efficient and user-friendly apps, but large bundles can cause performance issues and errors.
React’s Solution: React is a declarative, component-based toolkit for designing dynamic and interactive user interfaces. React’s solution relies on the Virtual DOM (VDOM), an in-memory Document Object Model. React may optimise efficiency and minimise expensive operations by first calculating differences between the virtual and real DOM and then applying just the necessary, minimal updates to the browser DOM.
React.lazy(): React.lazy() dynamically imports React components. Instead of statically importing a component at the top of your project (import MyComponent from ‘./MyComponent’);), React.lazy() lets you load it when rendered.
Suspense: Pre-installed React component Suspense uses React.lazy(). Suspense shows a fallback message or user interface while a component wrapped in Suspense is loading (i.e., its bundle hasn’t arrived yet). By signalling that material is loading, this avoids a blank screen and improves user experience. It is anticipated that Suspense will be able to manage data loading for more than simply components in upcoming React versions.
Code Example:
let’s look at a RiverInformation component that shows information on rivers. It could be imported statically at first:
import React, { lazy, Suspense, useState, useReducer } from "react";
const RiverInfo = lazy(() =>
Promise.resolve({
default: ({ name }) => {
const data = {
nile: ["The Nile River", "Longest river in the world, 6,650 km."],
amazon: ["The Amazon River", "Largest by discharge, ~6,400 km."],
yangtze: ["The Yangtze River", "Longest in Asia, 6,300 km."],
mississippi: ["The Mississippi River", "Major river in North America, 3,730 km."]
};
const [title, info] = data[name.toLowerCase()];
return (
<div className="p-4 bg-white rounded shadow">
<h3 className="text-xl font-bold">{title}</h3>
<p>{info}</p>
</div>
);
}
})
);
export default function App() {
const [river, setRiver] = useState("nile");
const [show, toggle] = useReducer((s) => !s, true);
const buttons = ["nile", "amazon", "yangtze", "mississippi"];
return (
<div className="p-6 text-center bg-blue-50 min-h-screen">
<h1 className="text-3xl font-bold mb-4">World's Longest Rivers</h1>
<div className="flex gap-2 justify-center mb-4">
{buttons.map((r) => (
<button
key={r}
onClick={() => setRiver(r)}
className={`px-4 py-1 rounded {river === r ? "bg-blue-600 text-white" : "bg-white border"}`}
>
{r[0].toUpperCase() + r.slice(1)}
</button>
))}
</div>
<button onClick={toggle} className="bg-indigo-600 text-white px-4 py-2 rounded mb-4">
{show ? "Hide Details" : "Show Details"}
</button>
{show && (
<Suspense fallback={<div className="p-4 bg-yellow-100 rounded">Loading...</div>}>
<RiverInfo name={river} />
</Suspense>
)}
</div>
);
}
Output:
World's Longest Rivers
Nile Amazon Yangtze Mississippi
Hide Details
The Nile River
Longest river in the world, 6,650 km.
Explanation of the Code
React performance optimisation uses code splitting, as shown in the code. This method uses React.lazy() and to load component code only when needed. The RiverInformationComponent’s code is stored in a separate file a(or simulated file) instead of the initial main application bundle. Clicking the “Show Details” button sets the show state to true, prompting React to render the component. Since the code is not yet accessible, the component displays the “Loading River Information…” message instead of rendering.
To load code, React.lazy() calls a dynamic import. After a simulated wait, React replaces the loading message with the fully rendered RiverInformationComponent. This procedure only downloads the code for the areas of the application the user is actively viewing, speeding up initial load time and improving user experience. River buttons modify the presented data, which is a component update and does not require another code split.
Benefits of Code Splitting
Reduced Initial Load Time: From this phase, you can load components asynchronously to split huge applications into smaller, more focused portions. You’ve only loaded data asynchronously, but you can load components too. Code splitting reduces the size of code bundles so users don’t have to download the complete application if they only need a piece.
Improved User Experience: React.js creates quick, responsive, and intuitive apps that improve user experience.
React uses a programming technique called Virtual DOM (VDOM) to keep an ideal version of the UI in memory and sync it with the real DOM. By just changing updated DOM elements, React reduces DOM manipulations rather than reloading the page when data changes.
Efficient Usage: For effective utilisation, React.js minimises costly activities and optimises application data processing and rendering. This performance is due to React’s Virtual DOM (VDOM), an in-memory UI representation that calculates the minimum browser DOM updates.
On-Demand Features: Lazy loading, code splitting, and asynchronous data handling provide on-demand functionality in React.js, making applications quick and responsive by loading just what’s needed. Code splitting lets customers download huge applications in smaller portions instead of all at once.
Conclusion
To sum up, code splitting in React.js is an effective optimisation method that greatly improves application speed, especially for substantial projects. By using tools like Suspense and React.lazy(), developers can optimise page load speeds and minimise the size of the first JavaScript bundle by loading components only when required. By displaying a useful backup user interface while loading, this method gives consumers on slower networks a better, more responsive experience while also reducing needless data transfer. In conjunction with React’s effective Virtual DOM updates, code splitting contributes to the development of quick, efficient, and intuitive applications that scale effectively without sacrificing performance or usability.