| How to Profile React Apps with DevTools :👈 | 👉:Code Splitting and Lazy Loading in React |
How to Reduce React Application Bundle Size |
How to Reduce React Application Bundle Size
1. What Is Bundle Size in React?
Bundle size refers to the size of the JavaScript and CSS files generated when a React application is built for production.
During development, a React application may contain multiple source files, components, libraries, and dependencies. A build tool such as Vite or Webpack processes these files and generates optimized assets that browsers can download.
Example:
React Application
|
+---- Components
+---- Pages
+---- JavaScript
+---- CSS
+---- Third-party Libraries
|
v
Build Process
|
v
Production Bundle
|
+---- JavaScript files
+---- CSS files
+---- Images and assets
A large bundle can cause:
- Slower initial page loading.
- Increased network usage.
- Longer JavaScript parsing and execution time.
- Slower application startup, especially on mobile devices.
- Reduced user experience on slower networks.
2. Measure Bundle Size Before Optimizing
Before optimizing, identify which files and dependencies contribute most to the bundle size.
For Vite Applications
Run the production build:
npm run build
Vite displays the generated assets and their sizes.
Example:
dist/
|
+---- index.html
|
+---- assets/
|
+---- index-a8d23.js 850 KB
+---- index-b7f21.css 120 KB
+---- vendor-c3d45.js 500 KB
These are illustrative values.
For Webpack Applications
You can use Webpack Bundle Analyzer to visualize the size of individual modules and dependencies.
Install:
npm install --save-dev webpack-bundle-analyzer
Configure the analyzer in your Webpack configuration:
const BundleAnalyzerPlugin =
require("webpack-bundle-analyzer")
.BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin()
]
};
After building the application, the analyzer displays a visual representation of the bundle.
For Vite Applications
You can use the Rollup Visualizer plugin to analyze Vite production bundles.
Install:
npm install --save-dev rollup-plugin-visualizer
Configure it in vite.config.js:
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import { visualizer } from "rollup-plugin-visualizer";
export default defineConfig({
plugins: [
react(),
visualizer({
open: true,
filename: "bundle-report.html",
gzipSize: true,
brotliSize: true
})
]
});
Run:
npm run build
The report helps identify large libraries and modules that contribute to the bundle.
3. Use Tree Shaking
Tree shaking is a build-time optimization that removes unused exports from JavaScript modules.
For example, suppose you import an entire utility library when you only need one function.
Before Optimization
import * as utils from "lodash";
const result = utils.debounce(() => {
console.log("Search");
}, 300);
Depending on the package and build configuration, this import can make it harder for the bundler to remove unused code.
After Optimization
import debounce from "lodash/debounce";
const result = debounce(() => {
console.log("Search");
}, 300);
Alternatively, use a tree-shakable package such as lodash-es with named imports:
import { debounce } from "lodash-es";
Benefits:
- Removes unused code.
- Reduces JavaScript bundle size.
- Reduces unnecessary downloaded dependencies.
Important: Tree shaking works best with ES modules and packages that expose compatible module formats. It is also affected by package side effects and build configuration.
4. Use Code Splitting
Code splitting divides a large JavaScript bundle into smaller files that can be loaded when required.
Instead of loading every page and component when the application starts, load only the code needed for the current page.
Without Code Splitting
Application Starts
|
v
Load All Pages
|
+---- Home
+---- Products
+---- Orders
+---- Reports
+---- Settings
All page-related JavaScript may be included in the initial bundle.
With Code Splitting
This reduces the amount of JavaScript required for the initial page load.
5. Use React.lazy and Suspense
React.lazy allows components to be loaded dynamically when they are needed.
Without Lazy Loading
import Home from "./pages/Home";
import Products from "./pages/Products";
import Reports from "./pages/Reports";
function App() {
return (
<div>
<Home />
<Products />
<Reports />
</div>
);
}
All three components are imported statically.
With Lazy Loading
import React, { lazy, Suspense } from "react";
const Home = lazy(() => import("./pages/Home"));
const Products = lazy(() => import("./pages/Products"));
const Reports = lazy(() => import("./pages/Reports"));
function App() {
return (
<Suspense fallback={<p>Loading page...</p>}>
<Home />
<Products />
<Reports />
</Suspense>
);
}
export default App;
React.lazy loads a component when React first attempts to render it.
Important: In this example, all three components are still rendered, so they will all be loaded. The main benefit appears when lazy-loaded components are conditionally rendered or used through route-based loading.
Practical Example: Route-Based Lazy Loading
import React, { lazy, Suspense } from "react";
import {
BrowserRouter,
Routes,
Route
} from "react-router-dom";
const Home = lazy(() => import("./pages/Home"));
const Products = lazy(() => import("./pages/Products"));
const Reports = lazy(() => import("./pages/Reports"));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route
path="/products"
element={<Products />}
/>
<Route
path="/reports"
element={<Reports />}
/>
</Routes>
</Suspense>
</BrowserRouter>
);
}
export default App;
Now the application can load the JavaScript for each page when the user navigates to that route.
6. Avoid Importing Entire Libraries
Some libraries contain many features, but your application may use only a small portion of them.
Importing unnecessary functionality can increase bundle size.
Example: Date Libraries
Instead of choosing a large date library without evaluating its size, consider whether a smaller library such as date-fns or Day.js meets your requirements.
Example using date-fns:
import { format } from "date-fns";
const formattedDate = format(
new Date(),
"dd-MM-yyyy"
);
Choose libraries based on required functionality, locale support, time-zone requirements, and bundle impact.
Example: Icon Libraries
Avoid importing an entire icon collection when only a few icons are needed.
For example, with a compatible tree-shakable icon package:
import { Search, User, Settings } from "lucide-react";
Check the generated bundle to confirm that unused icons are excluded.
7. Remove Unused Dependencies
Unused npm packages can increase maintenance overhead and may contribute to bundle size if they are imported into the application.
List installed dependencies:
npm list --depth=0
Review your package.json and remove packages that are no longer required.
For example:
npm uninstall unused-package
Also review:
- Duplicate libraries providing the same functionality.
- Old packages that are no longer used.
- Large libraries used for very simple operations.
- Dependencies imported only in development but incorrectly included in production code.
8. Use Dynamic Imports for Heavy Features
Some features are not required immediately when the application starts.
Examples include:
- PDF generation.
- Excel export.
- Charts and reporting.
- Rich text editors.
- Large data visualization libraries.
- Advanced administration screens.
Instead of importing these libraries at the top level, load them when the user requests the feature.
Example: Dynamically Load a PDF Library
async function generatePDF() {
const { jsPDF } = await import("jspdf");
const doc = new jsPDF();
doc.text("React Application Report", 10, 10);
doc.save("report.pdf");
}
function App() {
return (
<button onClick={generatePDF}>
Download PDF
</button>
);
}
export default App;
Now the PDF library can be loaded only when the user clicks the Download PDF button.
9. Optimize Images and Static Assets
Bundle size optimization is not limited to JavaScript. Large images and other static assets can also affect page loading performance.
Recommended practices:
- Use WebP or AVIF images where appropriate.
- Compress images before uploading.
- Use responsive image sizes.
- Lazy-load images that are below the initial viewport.
- Avoid unnecessarily large background images.
- Use SVG for suitable vector graphics and icons.
Example: Lazy Load an Image
<img
src="/images/product.webp"
alt="Product"
loading="lazy"
/>
This tells the browser that the image can be loaded when it approaches the visible area.
Important: Do not lazy-load critical images such as the main above-the-fold hero image when doing so would delay the initial visual experience.
10. Use Production Build Optimizations
Development builds contain additional debugging information and development-specific behavior.
Always inspect the production build when evaluating bundle size.
For Vite
npm run build
Vite uses production build optimizations through its underlying bundling tools.
For Create React App
npm run build
For applications using Create React App, the production build applies optimizations such as minification and dead-code elimination where supported.
Note: Create React App is deprecated for new React applications. Existing applications can still use it, but new projects should consider modern React-supported frameworks or build tools such as Vite.
11. Use Minification and Compression
Minification removes unnecessary characters from JavaScript and CSS files, such as whitespace, comments, and certain redundant syntax.
Example:
Before Minification
function calculateTotal(price, quantity) {
const total = price * quantity;
return total;
}
After Minification
function calculateTotal(e,t){return e*t}
Minification reduces the size of files transferred to the browser.
You should also enable HTTP compression on your hosting server or CDN.
Common compression formats include:
- Gzip
- Brotli
Compression reduces network transfer size, although it does not change the original uncompressed bundle size.
12. Avoid Loading Heavy Libraries on the Initial Page
Consider an application with the following pages:
- Home
- Products
- Orders
- Reports
- Administration
Suppose the Reports page uses a large charting library, while the Home page does not need it.
Importing the charting library in a shared top-level module may cause it to be included in the initial bundle.
A better approach is to import the charting component dynamically inside the Reports page.
import React, { lazy, Suspense } from "react";
const ReportsChart = lazy(
() => import("./ReportsChart")
);
function Reports() {
return (
<div>
<h2>Reports</h2>
<Suspense fallback={<p>Loading chart...</p>}>
<ReportsChart />
</Suspense>
</div>
);
}
export default Reports;
This allows the chart-related code to be loaded when the Reports page is visited.
13. Use Bundle Analysis to Identify Large Dependencies
After applying optimizations, generate another bundle report.
For example:
| Dependency | Illustrative bundle size | Possible action |
|---|---|---|
| React and React DOM | 140 KB | Usually required; avoid unnecessary duplicate copies. |
| Charting library | 450 KB | Load only on reporting pages. |
| Date library | 180 KB | Evaluate a smaller alternative or selective imports. |
| Icon library | 120 KB | Import only required icons. |
| Utility library | 100 KB | Use selective imports or native JavaScript where suitable. |
These values are illustrative only. Actual sizes depend on the package versions, build configuration, imported features, and compression.
Use the analyzer to decide which dependencies deserve attention rather than assuming that every large package can or should be removed.
14. Bundle Size vs Runtime Performance
Reducing bundle size improves loading performance, but it does not automatically solve every performance problem.
| Area | What it measures | Typical optimization |
|---|---|---|
| Bundle size | Amount of JavaScript and CSS delivered | Tree shaking, code splitting, removing unused dependencies |
| Initial loading | Time required to load and display the page | Reduce initial JavaScript, optimize images, use caching |
| Runtime performance | How efficiently the application executes | Optimize rendering, calculations, and state updates |
| Network performance | Time required to transfer resources | Compression, CDN, caching |
For example, React.memo can reduce unnecessary component rendering, but it does not directly reduce the JavaScript bundle size.
15. Best Practices to Reduce React Bundle Size
- Measure bundle size before making changes.
- Use a bundle analyzer to identify large dependencies.
- Use tree shaking wherever supported.
- Implement route-based code splitting.
- Use React.lazy and Suspense for suitable page-level components.
- Use dynamic imports for heavy features.
- Avoid importing entire libraries unnecessarily.
- Remove unused npm dependencies.
- Prefer smaller libraries when they satisfy the same requirements.
- Optimize images and static assets.
- Enable production minification.
- Enable Gzip or Brotli compression on the server or CDN.
- Measure the final bundle after every significant optimization.
16. Common Mistakes
Mistake 1: Assuming React.memo Reduces Bundle Size
React.memo is used to optimize component rendering. It does not remove unused JavaScript or reduce the size of imported libraries.
Mistake 2: Lazy Loading Every Component
Excessive code splitting can create many small requests and loading transitions. Focus on meaningful boundaries such as routes and large optional features.
Mistake 3: Using a Smaller Library Without Checking Requirements
A smaller library may not support the required functionality, time zones, locales, accessibility, or browser compatibility. Evaluate functionality as well as size.
Mistake 4: Measuring Only Development Bundle Size
Development builds are not representative of production output. Measure the production build.
Mistake 5: Ignoring Shared Dependencies
Splitting code into chunks does not always reduce the total amount of JavaScript downloaded. Check which chunks are loaded initially and which are loaded later.
17. Interview Questions and Answers
Q1. What is bundle size in React?
Bundle size is the size of the JavaScript and CSS assets generated during the production build of a React application.
Q2. What is tree shaking?
Tree shaking is a build-time optimization that removes unused exports from JavaScript modules to reduce the final bundle size.
Q3. What is code splitting?
Code splitting divides an application into smaller JavaScript chunks so that only the required code is loaded when needed.
Q4. What is React.lazy?
React.lazy allows a component to be loaded dynamically using an import function. It is commonly used with Suspense for loading states.
Q5. What is the difference between lazy loading and code splitting?
Code splitting creates separate bundles or chunks. Lazy loading delays loading a resource until it is needed. React.lazy uses dynamic imports to support component-level lazy loading.
Q6. Does React.memo reduce bundle size?
No. React.memo primarily reduces unnecessary component rendering when its props have not changed. It does not remove unused code from the production bundle.
Q7. How do you identify large dependencies?
Use tools such as Webpack Bundle Analyzer or Rollup Visualizer to inspect the production bundle and identify large modules.
Q8. What is the difference between Gzip and Brotli?
Both are compression formats used to reduce the amount of data transferred over the network. Brotli often provides better compression for web assets, although actual results depend on the content and compression settings.
Q9. Does code splitting always reduce total bundle size?
No. Code splitting primarily reduces the amount of JavaScript loaded initially. The total amount of JavaScript across all chunks may remain similar.
Q10. How would you optimize a React application with a large initial bundle?
First, analyze the production bundle to identify large dependencies. Then apply tree shaking, remove unused packages, implement route-based code splitting, dynamically load heavy features, and optimize static assets. Finally, compare the initial and total bundle sizes after optimization.
18. Quick Summary
| Technique | Purpose |
|---|---|
| Tree Shaking | Remove unused JavaScript exports. |
| Code Splitting | Divide large bundles into smaller chunks. |
| React.lazy | Load components dynamically. |
| Dynamic Imports | Load heavy libraries only when required. |
| Selective Imports | Avoid importing unnecessary library features. |
| Dependency Cleanup | Remove unused packages. |
| Image Optimization | Reduce static asset transfer size. |
| Minification | Remove unnecessary characters from production files. |
| Gzip / Brotli | Reduce network transfer size. |
| Bundle Analyzer | Identify large dependencies and modules. |
Key takeaway: The most effective way to reduce React application bundle size is to measure the production bundle, identify unnecessary or large dependencies, implement tree shaking and code splitting, and load heavy features only when required. Always measure the results after optimization.
| How to Profile React Apps with DevTools :👈 | 👉:Code Splitting and Lazy Loading in React |
Comments and Discussion