Menu

Optimising Bundles and Builds

Lesson 3: Optimising Bundles and Builds

Where does extra JavaScript come from?

Cause Fix
'use client' too high in the tree Move it down to small interactive components
Heavy libraries loaded on every page (charts, editors, maps) Load them only when needed with next/dynamic
Importing whole icon or utility libraries Use optimizePackageImports or direct imports
Third-party scripts (chat, analytics) blocking the page Load with next/script and a lazy strategy

Example

'use client';
import dynamic from 'next/dynamic';
import { useState } from 'react';

const CodePlayground = dynamic(() => import('./CodePlayground'), {
  loading: () => <p>Loading editor…</p>,
  ssr: false, // Editor needs the browser
});

export function LessonExercise() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button onClick={() => setOpen(true)}>Open playground</button>
      {open && <CodePlayground />}
    </>
  );
}
import Script from 'next/script';

<Script src="https://widget.chat.example/loader.js" strategy="lazyOnload" />

Inspect your bundles with the built-in Turbopack analyzer (available from Next.js 16.1):

npx next analyze

On versions 16.1 to 16.3 the command is next experimental-analyze. Webpack builds use the @next/bundle-analyzer plugin instead.

How it works

  • next/dynamic splits the editor into its own chunk, downloaded only when the button is clicked.
  • The analyzer shows each module's size by route and environment, and the import chain that pulled it in.
  • React Compiler (reactCompiler: true in next.config.ts) memoises components automatically, reducing re-renders. It is stable but off by default and increases build time.
  • Turbopack is the default bundler. Its file system cache speeds up repeat next dev and, since 16.3, next build runs.

Common mistakes

Mistake Effect Fix
ssr: false in a Server Component Error Use next/dynamic with ssr: false inside a Client Component
Lazy-loading above-the-fold content Slower LCP Lazy-load only what is hidden or below the fold
Adding useMemo everywhere by hand Noise, little gain Enable the React Compiler instead

Key takeaways

  • Measure bundles before optimising; the analyzer shows exactly what is large.
  • Lazy-load heavy, optional UI and third-party scripts.

Try it: Run the bundle analyzer on LearnHub, find the largest client module, and lazy-load it with next/dynamic.


Nextjs Tutorial

J

Jebasta





Get in Touch For Details