Skip to the solution
MediumFrontend4 min read

How does code splitting and next/dynamic work in Next.js?

553 views

The problem

Question presented to candidate: "Our dashboard page includes a heavy chart editor that most users never open. How does Next.js split code, and how would you keep the editor out of the initial bundle?"

What a strong answer should cover:

  • Next.js splits JavaScript per route automatically, and Server Components add no client JavaScript at all.
  • next/dynamic (built on React.lazy and Suspense) loads a Client Component in its own chunk when it is first rendered.
  • Options: loading for a placeholder, ssr: false to skip server rendering for browser-only components.
  • ssr: false is only allowed in Client Components; in a Server Component the build fails.
  • You can also await import() a library inside an event handler to load it on demand.

Clarifying questions expected:

  • "Is the component needed for the first view?" β€” if not, lazy load it.
  • "Does it use browser-only APIs?" β€” then ssr: false.

Code / implementation expected: Yes β€” a toggle that lazy loads a heavy component.

  • nextjs
  • code-splitting
  • next-dynamic
  • performance

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

4 min read Β· 8 sections

Read the code

Lazy loading a browser-only editor from a Client Component
// components/EditorToggle.tsx
"use client";
import { useState } from "react";
import dynamic from "next/dynamic";

const ChartEditor = dynamic(() => import("./ChartEditor"), {
  ssr: false,                                 // uses window; skip server rendering
  loading: () => <p>Loading editor...</p>,
});

export function EditorToggle() {
  const [open, setOpen] = useState(false);
  return (
    <div>
      <button onClick={() => setOpen(true)}>Edit chart</button>
      {open && <ChartEditor />}
    </div>
  );
}

// loading a library only in a handler
async function exportCsv(rows: string[][]) {
  const { unparse } = await import("papaparse");
  return unparse(rows);
}

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 69 of 129 in Next.js

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Next.js questions
Up nextMedium

What is JSON-LD structured data and how do you add it in Next.js?

Continue