React Code Splitting

What Is Code Splitting In React?

In your React Application, all code like components, libraries, dependencies and other files are combined or bundled into one big JavaScript file. when user open the app so this file sent to the browser and it cause a slower and load problem which effects on performance and user experience.

For this problem we use a Code Splitting method. Code splitting break your big JavaScript file into smaller parts (chunks). when any each file are needed so smaller file will load.

🔹 For example:

  • When you open your home page, so your homepage code will loads
  • When user visit’s your dashboard page’s, so only dashboard page code will loads.

Result:

  • Faster loading time, because only particular code are loaded.
  • Giving better performance.
  • User download only what they use, not the entire app.

Why Use Code Splitting?

The main reasons for using code splitting in React applications:

  1. Improved Performance: Code Splitting loads only required parts of applications, this reason reduces the user times.
  2. Optimized Load Time: Only necessary code is loaded, so users can access the applications basic features quickly.
  3. Better User Experience: User can easily interacting with application for it’s faster load time.

How Does Code Splitting Work in React?

React offers code-splitting capabilities via dynamic imports and React.lazy(), allowing developers to specify which parts of the code should be split.

When a user accesses a specific route or component, only the required code chunk is fetched and rendered, keeping the initial bundle light.

React use different tools for code Splitting method:

🔧 1. Webpack“The Code Splitter”

  • Webpack is a build tool, it split your code during the build process.
  • It creates a small files out of your large application.
  • For Example : Webpack is the worker, who cuts the pizza into slices.

🧳 2. Dynamic Imports (import() function)“The On-Demand Loader”

  • Dynamic Imports used in your code to tell React when to load specific part of code.
  • It is a JavaScript feature, that loads a module only when user visit a specific page.

✅ How to Install Webpack In React

🔧 Step-by-step Installation:

  1. Initialize your project:
npm init -y
  1. Install Webpack and Webpack CLI:
npm install --save-dev webpack webpack-cli
  1. Install Babel for JSX (if using React):
npm install --save-dev babel-loader @babel/core @babel/preset-env @babel/preset-react
  1. Create a basic Webpack config:
    create webpack.config.js In the root of your project:
const path = require('path');

module.exports = {
// Starting point of application
entry: './src/main.js',

// Final bundled output settings
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.bundle.js',
},

// Rules to handle different file types
module: {
rules: [
{
test: /\.jsx?$/, // Supports both .js and .jsx
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},

// Set development mode for better debugging
mode: 'development',
};
  1. Add Babel config:
    Create .babelrc file:
{
"presets": ["@babel/preset-env", "@babel/preset-react"]
}
  1. Add build script in package.json:
"scripts": {
"build": "webpack"
}
  1. Run:
npm run build

✅ If you are using Create React App So you don’t need to install Webpack manually, it is already included. and you can use dynamic imports directly using lazy() and Suspense.

✅ Raect.lazy() and React.Suspense use for code splitting

The Raect.lazy() and React.Suspense used for code splitting and loaded if they are needed.

This means that the component is not loaded until it has been rendered on the screen.

React.Suspense is a wrapper to when loading process happen so it is showing the loading message, spinner and etc.

Example:

import React, { Suspense } from 'react';

const LazyComponent = React.lazy(() => import('./LazyComponent'));

function App() {
return (
<div>
<h1>Welcome to the App</h1>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}

export default App;

In this example:

  • LazyComponent is imported dynamically using React.lazy().
  • Suspense show a fallback loading message or spinner while LazyComponent loads.

Important Tips: Code Splitting and Lazy loading are technically different.

Practical Example: Code Splitting by Route

When your app has multiple pages (like Home, About, Contact), Only required page are load.

Example:

import React, { Suspense } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';

// Lazy-loaded components with changed names
const HomePage = React.lazy(() => import('./pages/Home'));
const AboutSection = React.lazy(() => import('./pages/About'));
const ContactPage = React.lazy(() => import('./pages/Contact'));

function MainApp() {
return (
<Router>
<Suspense fallback={<div>Please wait, loading content...</div>}>
<Switch>
<Route exact path="/" component={HomePage} />
<Route path="/about" component={AboutSection} />
<Route path="/contact" component={ContactPage} />
</Switch>
</Suspense>
</Router>
);
}

export default MainApp;

In this example:

  • Each route (Homepage, AboutSection, ContactPage) is split into separate part.
  • The Suspense component provide a fallback UI (means spinner and loading message) while each route component are load.

Code Splitting with Webpack

Webpack splitChunks option automatically divide your code into smaller parts, It is called “chunks“.

Here a sample Webpack configuration for split chunks:

module.exports = {
optimization: {
splitChunks: {
chunks: 'all', // This will split all chunks in the app
},
},
};

In this example:

  • Setting chunks : ‘all’ instructs Webpack to split all code (including vendor code and dependencies) into separate chunks.
  • This method is specially helpful for take commonly used libraries, like React or Lodash and putting them into separate files.

Code Splitting Dashboard Application Use Case

In React Application, dashboard have a multiple like Analytics, Reports and User Settings. we can make all module code-split, it is helps to main dashboard loads quickly and additional module load only when needed.

Example:

import React, { Suspense } from 'react';

const Analytics = React.lazy(() => import('./modules/Analytics'));
const Reports = React.lazy(() => import('./modules/Reports'));
const UserSettings = React.lazy(() => import('./modules/UserSettings'));

function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<div>Loading Analytics...</div>}>
<Analytics />
</Suspense>
<Suspense fallback={<div>Loading Reports...</div>}>
<Reports />
</Suspense>
<Suspense fallback={<div>Loading User Settings...</div>}>
<UserSettings />
</Suspense>
</div>
);
}

export default Dashboard;

With this setup:

  • The ControlPanel component load instantly.
  • Individual modules (Analytics, Reports and User Settings) are loaded only when needed, which means if the user only visits the Analytics section, so only that module will load.

Code Splitting Considerations

  1. Error Handling: Network errors may prevent chunks from loading. It’s essential to handle errors in your fallback UI or catch any errors using error boundaries.
  2. Fallback UI: Always provide a Suspense fallback, so users have feedback while components load.
  3. Chunk Management: Avoid creating too many chunks, which can overwhelm the server with requests and slow down the application.

Limitations of Code Splitting

  • Complexity: code splitting may add complexity to the app structure.
  • Error Management: Sometime network issue may cause delay in loading chunks. that reason requiring error handling.
  • Potential Overuse: Much more splitting may result in too many HTTP requests, so it will impacting on performance.

Leave a Comment