Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

React Bundle Size: Cut Initial JS Without Next.js

· 7 min read · Home Tech

In this article
  1. Why Initial JavaScript Size Matters
  2. What's Actually in Your Initial Bundle?
  3. Code Splitting: Load Only What the Current Page Needs
  4. Tree Shaking and Side Effect Flags
  5. Replace Heavy Dependencies with Lighter Alternatives
  6. Manual Chunk Splitting and Dynamic Imports
  7. Common Mistakes and Misconceptions
  8. Frequently Asked Questions

You can reduce your React app's initial JavaScript bundle without migrating to Next.js by using code splitting, tree shaking, and dependency optimization. This article explains the practical techniques, from route-based splitting with React.lazy to replacing heavy libraries, that cut initial load time while keeping your current setup.

in t | Finish time | min | 50 | 0
in d | Distance | km | 10 | 0
out pace | Average pace | min/km | t / d | 2
out speed | Average speed | km/h | d / (t / 60) | 2

Why Initial JavaScript Size Matters

The initial JavaScript bundle is everything your browser must download, parse, and execute before the page becomes interactive. On a typical 4G connection, a 500 KB bundle can take several seconds just to download, and parsing that much code can block the main thread for another second or two. Users on slower devices or networks experience blank screens, delayed clicks, and higher bounce rates. Core Web Vitals like Largest Contentful Paint (LCP) and Time to Interactive (TTI) are directly affected by the size of your initial JS payload.

Next.js solves this with server-side rendering and automatic code splitting per page, but you don't need to migrate to get most of the benefit. The same principles—split code by route, load only what's needed, and shrink dependencies—can be applied to any React app built with Create React App, Vite, or a custom Webpack setup.

What's Actually in Your Initial Bundle?

Before optimizing, you need to know what you're shipping. Use a bundle analyzer to see the composition of your main chunk. For Webpack, run npx source-map-explorer build/static/js/*.js or use webpack-bundle-analyzer. For Vite, rollup-plugin-visualizer shows the same detail.

Common culprits include:

  • Entire UI libraries imported without tree shaking (e.g., importing all of lodash instead of just _.debounce)
  • Large date libraries like Moment.js (over 300 KB minified) when you only need one formatting function
  • Charting libraries, data grids, or rich text editors loaded even if only one page uses them
  • Polyfills included for older browsers that most of your users don't use
  • Duplicate dependencies from different versions of the same package

Run the analyzer, note the largest modules, and prioritize those. Often 20% of dependencies account for 80% of the bundle size.

Code Splitting: Load Only What the Current Page Needs

Code splitting breaks your single bundle into smaller chunks that load on demand. The most effective split is by route: each page gets its own chunk, loaded only when the user navigates to it.

With React Router, you can use React.lazy and Suspense to achieve this without any server changes:

import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';

const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Reports = lazy(() => import('./pages/Reports'));

function App() {
  return (
    <BrowserRouter>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/reports" element={<Reports />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}

Webpack and Vite automatically create separate chunks for each dynamic import(). The initial bundle then contains only the router, the layout, and the code for the first route. The other pages' code is fetched only when the user navigates there.

You can also split heavy components that are below the fold or only appear after user interaction (e.g., a modal, a tooltip, or a chart that appears after clicking a button). Use the same React.lazy pattern for those.

Tree Shaking and Side Effect Flags

Tree shaking removes unused exports from your final bundle. It works when you import named exports from ES modules, not when you import the whole module. For example:

// Bad: pulls in the entire lodash library
import _ from 'lodash';
_.debounce(fn, 300);

// Good: only the debounce function is included
import debounce from 'lodash/debounce';
debounce(fn, 300);

For libraries that ship ES modules (like date-fns, RxJS, or lodash-es), named imports are tree-shakeable. For CommonJS libraries, you may need to use the per-module path (e.g., lodash/debounce) or rely on a babel plugin like babel-plugin-lodash.

Sometimes tree shaking fails because a package has side effects in its top-level code. In your package.json, add "sideEffects": false to tell bundlers it's safe to drop unused exports. If you have CSS or polyfill files that must be kept, list them explicitly:

"sideEffects": ["*.css", "./src/polyfills.js"]

Check your bundler's output after enabling this—you'll often see a 10–30% reduction just from this flag.

Replace Heavy Dependencies with Lighter Alternatives

Some libraries are so large that no amount of tree shaking helps. Replace them with smaller, focused alternatives:

  • Moment.js (327 KB) → date-fns (7 KB per function) or Day.js (2 KB)
  • Lodash (526 KB) → native Array methods, or import only the specific functions
  • jQuery (87 KB) → native DOM APIs (if you still use it)
  • FullCalendar (300+ KB) → a lightweight calendar like react-big-calendar or a custom grid
  • Recharts (100+ KB) → if you only need simple charts, consider chart.js (60 KB) or lightweight SVG

For date formatting, Day.js is a drop-in replacement for Moment.js in most cases. For data manipulation, native map, filter, and reduce cover most needs. If you must keep a heavy library, load it only on the page that uses it via code splitting.

Manual Chunk Splitting and Dynamic Imports

Beyond route splitting, you can manually split vendor libraries into separate chunks. In Webpack, use splitChunks to separate React itself from your app code, or to group rarely-changing dependencies into a single long-cacheable chunk:

// webpack.config.js
optimization: {
  splitChunks: {
    cacheGroups: {
      react: {
        test: /[\\/]node_modules[\\/](react|react-dom)[\\/]/,
        name: 'react',
        chunks: 'all',
      },
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendor',
        chunks: 'all',
      },
    },
  },
}

This doesn't reduce the total bytes downloaded, but it improves caching: the React chunk changes only when React updates, so returning users don't re-download it. For Vite, use build.rollupOptions.output.manualChunks similarly.

You can also use dynamic imports for non-UI logic. For example, if you have a large utility that's only needed after a user action, load it on demand:

async function handleExport() {
  const { exportToCSV } = await import('./utils/export');
  exportToCSV(data);
}

This moves the utility's code out of the initial bundle entirely.

Common Mistakes and Misconceptions

Mistake: Splitting everything. Over-splitting creates many small HTTP requests, which can be slower than one larger request on HTTP/1.1. HTTP/2 mitigates this, but there's still overhead. Split at the route level and for truly heavy components, not for every button.

Mistake: Ignoring the fallback. When you use React.lazy, you must wrap it in Suspense with a fallback UI. If you forget, the app crashes. The fallback can be a simple spinner, but it should be small and not block rendering.

Misconception: "Tree shaking automatically removes everything unused." Tree shaking only works with ES modules and only if the package doesn't have side effects. Many popular packages still ship CommonJS, so you need the per-path import or a babel plugin.

Mistake: Not measuring before and after. Always record your initial bundle size before changes and after. Use gzip or brotli sizes, since that's what the browser downloads. A 10% reduction in raw size might be 20% after compression.

Misconception: "Next.js is the only way to get fast initial load." Server-side rendering helps with perceived speed, but a well-optimized client-side React app can achieve similar TTI. The techniques above work in any React setup.

Frequently Asked Questions

Q: Will code splitting hurt SEO? No. Google renders JavaScript, and as long as your content is available after the initial load (even if it's in a lazy chunk), it will be indexed. For critical content, you can use server-side rendering or pre-rendering, but for most SPAs, client-side rendering with code splitting is fine.

Q: How much can I realistically reduce my bundle? Typical reductions are 30–60% after removing unused dependencies, switching to lighter libraries, and route splitting. If you have a large Moment.js or Lodash dependency, replacing it alone can cut 300–500 KB.

Q: Does this work with Create React App? Yes. CRA supports React.lazy and dynamic imports out of the box. For manual chunk splitting, you'll need to eject or use a tool like craco to override the Webpack config.

Q: What about React 18 and concurrent features? React 18's Suspense works the same for code splitting. You can also use startTransition to mark non-urgent updates, but that doesn't affect bundle size.

Q: Should I use a CDN for React? Using a CDN for React (like unpkg) can reduce your bundle size, but it creates a separate dependency and complicates versioning. It's generally better to bundle React with your app and rely on long-term caching.

Q: Is gzip or Brotli better? Brotli compresses better (about 20% smaller than gzip) and is supported by all modern browsers. Most hosting providers enable it automatically. Check your server's response headers to confirm.