Skip to article content
LESSON 21 / 28

Performance, images, and JavaScript cost

Measure the work required to display and interact with a page, then reduce the part that actually dominates.

What you will be able to do

  • Distinguish server latency, transfer cost and main-thread work.
  • Reduce client module boundaries and optional dependencies.
  • Reserve image space and choose responsive loading behavior.
  • Compare repeatable before-and-after evidence.

Optimize the slow path you can observe

A page can be slow before its first byte, while downloading assets, or while the browser parses and executes JavaScript. A small bundle does not fix a slow database query. A fast server does not fix a huge interactive chart. Start by recording the user action and measuring the relevant phases under a repeatable device and network condition.

Use a route-level budget as a design aid, not as a fabricated performance score. Track the resources required before the main content can be used, the JavaScript introduced by a client boundary, and interaction delays during expensive updates. State whether a number comes from a local lab measurement or real-user telemetry; they answer different questions.

Move boundaries before adding memoization

A top-level use client directive can pull a large import graph into the browser. Keep static layout and server data work on the server and isolate the small interactive leaf. Passing a compact DTO also limits payload size. Review heavy dependencies before optimizing small expressions; eliminating a library from the initial client graph can change more than memoizing a mapping loop.

Lazy loading helps optional features such as an editor opened after a button click. It introduces a loading state and does not make required work disappear. The self-contained example loads a local client panel only after the user asks for it. Browser-only libraries that touch window during import may need a client wrapper and appropriate SSR handling; do not turn off SSR for the entire site as a blanket fix.

Client module

app/catalog/optional-panel.tsx
"use client";
import dynamic from "next/dynamic";
import { useState } from "react";
const DetailsPanel = dynamic(() => import("./details-panel"), {
  loading: () => <p role="status">Loading detailed analysis...</p>,
});
export default function OptionalPanel() {
  const [open, setOpen] = useState(false);
  return <section>
    <button type="button" onClick={() => setOpen(true)}>Open detailed analysis</button>
    {open ? <DetailsPanel /> : null}
  </section>;
}

Client module

app/catalog/details-panel.tsx
"use client";
export default function DetailsPanel() {
  return <p>Detailed analysis is ready.</p>;
}

PAUSE AND PREDICT

A catalogue feels slow. Which first step produces useful evidence?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Reserve space and send the right resource

Images need correct dimensions or a constrained fill container so layout space exists before bytes arrive. Responsive sizes should describe the rendered width, allowing a suitable source to be selected. Loading every image eagerly competes with the primary content. Prefer deliberate loading for the important visible image and defer images that are genuinely below the fold.

Restrict remote image sources rather than turning an optimization endpoint into an arbitrary fetcher. Give informative images useful alternative text and decorative images an empty alternative. Font choices affect transfer, text display and layout shift, so limit weights and scripts to actual needs. A performance improvement that removes readable text, semantics or keyboard access is a regression.

Prefetch selectively and inspect requests

Prefetching trades earlier work for faster future navigation. A list with hundreds of destinations may create avoidable server and network activity if every destination is eagerly prepared. Current Next.js behavior depends on the version and Partial Prefetching configuration, so inspect actual requests instead of repeating a universal claim about what Link always downloads.

For a machine-coding task, use sensible defaults, then test likely transitions. A product detail route benefits from useful prefetched structure; an expensive rarely opened analytics route may not. Keep browser history, loading feedback and focus behavior working when optimizing navigation. Fast transitions that leave the user uncertain about the current page are incomplete.

PAUSE AND PREDICT

A compressed image still shifts the product text when it loads. What is missing?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Make one change and preserve the contract

Record the baseline, identify a bottleneck, change one relevant design decision and repeat the same scenario. Compare the main content timing, transfer size and interaction behavior. Check both cold and warm loads when caching matters. Do not report a single best run as a universal guarantee, and do not equate a green synthetic score with every user having a fast experience.

The kata deduplicates an illustrative initial module graph and reports whether it exceeds a byte budget. It is accounting practice, not a bundler analyzer or a Web Vital measurement. After solving it, inspect a real build and explain why a shared dependency should be counted once while a deferred chunk should not be counted as initial work.

Misconceptions to replace

Compare the tempting shortcut with the model you can verify in code.

CLAIM TO CHALLENGEServer Components mean no JavaScript reaches the browser.
A more accurate model

Client Components and their imported dependencies still ship browser code.

How to check it

Inspect the server/client module boundary and an actual build.

CLAIM TO CHALLENGELazy loading removes the cost of an optional feature.
A more accurate model

It defers that work and needs useful loading/error behavior on first use.

How to check it

Next.js lazy-loading guide and the optional-panel exercise.

Mistakes to catch in your own code

  • Optimizing useMemo before measuring the dominant cost.
  • Putting the entire application under use client.
  • Using inaccurate sizes values or unbounded remote images.
  • Reporting simulated byte budgets as measured production performance.

Write it by hand

JavaScript logic playground

Account for the initial module budget

Implement solve(input). This sandbox runs the lesson's logic with FrontendX's isolated code runner. Next.js server behavior is verified in the project lab below.

  1. Input is {modules,budget}; modules contain {id,bytes,initial}.
  2. Include only initial modules, and count repeated IDs once using the largest declared bytes for that ID.
  3. Return {bytes,overBudget,ids} with sorted included IDs. This is an illustrative accounting model, not build output.

Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.

Ready when you are. Try the exercise before opening the worked solution.
Inspect 3 test cases
  1. Deduplicate a shared module

    Input

    {
      "modules": [
        {
          "id": "react",
          "bytes": 100,
          "initial": true
        },
        {
          "id": "react",
          "bytes": 100,
          "initial": true
        },
        {
          "id": "page",
          "bytes": 40,
          "initial": true
        }
      ],
      "budget": 150
    }

    Expected

    {
      "bytes": 140,
      "overBudget": false,
      "ids": [
        "page",
        "react"
      ]
    }
  2. Exclude deferred work

    Input

    {
      "modules": [
        {
          "id": "editor",
          "bytes": 900,
          "initial": false
        },
        {
          "id": "shell",
          "bytes": 50,
          "initial": true
        }
      ],
      "budget": 40
    }

    Expected

    {
      "bytes": 50,
      "overBudget": true,
      "ids": [
        "shell"
      ]
    }
  3. Keep the larger duplicate estimate

    Input

    {
      "modules": [
        {
          "id": "a",
          "bytes": 10,
          "initial": true
        },
        {
          "id": "a",
          "bytes": 20,
          "initial": true
        }
      ],
      "budget": 20
    }

    Expected

    {
      "bytes": 20,
      "overBudget": false,
      "ids": [
        "a"
      ]
    }
Reveal the worked solution and reasoning
solution.js
function solve(input) {
  const included = new Map();
  for (const item of input.modules) {
    if (item.initial) included.set(item.id, Math.max(included.get(item.id) || 0, item.bytes));
  }
  const bytes = [...included.values()].reduce((sum, value) => sum + value, 0);
  return { bytes, overBudget: bytes > input.budget, ids: [...included.keys()].sort() };
}

A Map gives one contribution per module identity.

Maximum duplicate size makes the exercise deterministic when the illustrative manifest disagrees.

Real bundle tooling has chunking, compression and runtime details beyond this model.

Verify it in a real Next.js application

Next.js application lab

Measure the catalogue before adding optional client work

Open the local application route /catalog after starting the workbench. Follow the experiment and collect the evidence described below.

Make the change

  1. Build and start the pinned project, then record a cold /catalog load, a soft product-modal navigation and a direct /catalog/keyboard visit. Keep viewport, network throttling and browser cache conditions consistent.
  2. Inspect the cached server catalogue and the small AddToCart client control. The existing catalogue is text-based; it does not yet contain a product-image optimization or a heavyweight optional-panel experiment.
  3. Implementation extension: add an optional interactive panel behind a deliberate client boundary and dynamic import. Compare its download and main-thread work before opening it and after the user requests it.
  4. Implementation extension: add realistic product images with explicit dimensions, an appropriate responsive sizes contract and a justified loading priority. Measure the resulting LCP and layout stability instead of assuming that an image component guarantees an improvement.
  5. Record before/after observations for one change at a time and explain whether it affected server work, transferred JavaScript, render delay or interaction responsiveness.

Check the behavior

  • The baseline catalogue and product content remain readable while streamed work is pending.
  • The optional-panel extension loads the intended chunk at the intended interaction and retains an accessible loading state.
  • Image and JavaScript improvements are supported by comparable browser observations; the shipped project has no precomputed performance score.
  • The report names the production build, cache state and conditions so another learner can repeat the comparison.
Review the application reasoning

The kata checks performance-budget arithmetic. This lab provides a measurable routing and rendering baseline; asset optimization and dependency-reduction experiments are implementation assignments.

Open the project files and run instructions

A complete App Router application with catalogue routing, cart state, a task dashboard, practice sessions, tenant checks, cached data, hydration repairs, and HTTP streaming. Next.js 16.4.6 and React 19.3.0 are pinned in the project.

The playground opens a new editable copy. A local Node.js 22.14+ installation also runs the project. Use the local production build when measuring caching, streaming, or deployment behavior.

Terminal
cd nextjs-interview-lab
npm ci
npm run dev

# In a second terminal
npm test

# Stop dev, then verify the production application
npm run build
npm start

# In a second terminal, install the test browser once
npx playwright install chromium
npm run test:e2e

Open http://localhost:3003. The project includes a credential-free practice account selector and a single-process file store. Those choices make experiments reproducible; the security and deployment lessons show what a production system needs.

Explain it in an interview

Give your answer aloud before opening the explanation. Then answer the follow-ups using your implementation as evidence.

  1. 01What would you inspect first on a slow Next.js page?

    I would reproduce a specific slow load or interaction and separate server waiting, resource transfer and browser execution. That tells me whether to inspect queries, waterfalls, assets or client work.

    I would establish a repeatable baseline before changing code. The first fix should target the observed dominant cost, not a favorite optimization technique.

    Follow-up questions

    • How would you distinguish cold from warm cache behavior?
    • What if local results differ from real users?
  2. 02Do Server Components remove all JavaScript from the browser?

    No. Interactive Client Components and their imported dependencies still require browser code. Server Components reduce what needs to ship when their work remains outside the client module graph.

    I inspect the actual boundary and imports. Making a large ancestor a Client Component can undo much of that benefit even if some data was fetched on the server.

    Follow-up questions

    • What does a client provider import?
    • Can server-rendered HTML still require hydration?
  3. 03What is the cost of lazy loading a feature?

    The initial route can ship less optional code, but the first use must fetch and initialize that feature. It needs a meaningful loading state and error handling.

    I would not defer essential content just to improve a superficial metric. The decision depends on how likely and how urgent the interaction is.

    Follow-up questions

    • Would you preload on user intent?
    • What if the imported library touches window at module scope?
  4. 04Why can an optimized image still cause layout shift?

    Compression does not reserve layout space. If dimensions or the fill container are missing or wrong, content can move when the image's size becomes known.

    I establish the aspect ratio, use responsive sizing that matches layout and check visible loading behavior. I also preserve alternative text and source restrictions.

    Follow-up questions

    • Which image should load eagerly?
    • How do you test the mobile width?

Check your understanding

Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.

FINAL KNOWLEDGE CHECK

The kata reports a lower initial byte budget. What can you truthfully conclude?

Choose one answer, then check your reasoning.

This check does not mark the lesson as solved.

Your checkpoint

Mark what you can do independently

Loading your local progress.

Sources and further reading

© 2026 FrontendX. All rights reserved.