ReactMedium

Bundle size optimization?

Reduce bundle size by shipping less code to the browser: split code by route and feature, remove unused code (tree shaking, ES modules, avoiding barrel-file bloat), replace heavy dependencies with lighter ones or native APIs, move work to the server (SSR, Server Components), and measure regularly with a bundle analyzer.

Techniques

  1. Analyze first: rollup-plugin-visualizer (Vite), source-map-explorer, @next/bundle-analyzer or next analyze. Find the largest modules.
  2. Code splitting: lazy() for routes and heavy components; dynamic import() for rarely used libraries.
  3. Tree shaking: use ES module builds and named imports (import { debounce } from "lodash-es", not the whole lodash). Packages should declare "sideEffects": false.
  4. Lighter alternatives: date-fns or Intl instead of moment; native fetch instead of a client library when its features are not needed; structuredClone instead of deep-clone libraries.
  5. Avoid duplicate dependencies: dedupe versions in the lockfile.
  6. Icons: import individual icons, not the full set.
  7. Polyfills: target modern browsers (Vite's default targets are modern) and avoid shipping unnecessary polyfills.
  8. Server Components or SSR: keep markdown parsers, date formatting and data logic on the server.
  9. Compression: Brotli or gzip on the server or CDN.
  10. Minification: done by default (Oxc in Vite 8, SWC in Next.js).

Budgets

Set size budgets in CI and fail builds that exceed them, so regressions are caught early.

Also measure the user impact

Smaller bundles improve LCP and INP, especially on mobile devices where parsing and executing JavaScript is expensive.

Code example

tsx
1// vite.config.ts - analyze and split
2import { defineConfig } from "vite";
3import react from "@vitejs/plugin-react";
4import { visualizer } from "rollup-plugin-visualizer";
5
6export default defineConfig({
7 plugins: [react(), visualizer({ filename: "stats.html", gzipSize: true })],
8});
9
10// Before: whole libraries in the main chunk
11// import _ from "lodash";
12// import moment from "moment";
13// import * as Icons from "lucide-react";
14
15// After: named imports, native APIs, lazy-loaded heavy features
16import debounce from "lodash-es/debounce";
17import { Search } from "lucide-react";
18import { lazy } from "react";
19
20export const formatDate = (d: Date) => new Intl.DateTimeFormat("en-GB", { dateStyle: "medium" }).format(d);
21export const onSearch = debounce((q: string) => console.log(q), 300);
22export const SearchIcon = Search;
23export const MarkdownEditor = lazy(() => import("./markdown-editor"));

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app