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.
Before this lesson
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
"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
"use client";
export default function DetailsPanel() {
return <p>Detailed analysis is ready.</p>;
}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.
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.
- Input is {modules,budget}; modules contain {id,bytes,initial}.
- Include only initial modules, and count repeated IDs once using the largest declared bytes for that ID.
- 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.
Inspect 3 test cases
- 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" ] } - 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" ] } - 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
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
- 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.
- 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.
- 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.
- 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.
- 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.
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:e2eOpen 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.
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?
- Fetching dataOfficial documentation
- Lazy loadingOfficial documentation
- Image optimizationOfficial documentation
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?
- Server and client boundaryOfficial documentation
- Server and Client ComponentsOfficial documentation
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?
- Lazy loadingOfficial documentation
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?
- Image optimizationOfficial documentation
Check your understanding
Answer these without reopening the worked examples. The feedback explains the reasoning and the misconception behind each choice.
Your checkpoint
Loading your local progress.
Sources and further reading
- Server and client boundaryOfficial documentation
- Server and Client ComponentsOfficial documentation
- Fetching dataOfficial documentation
- Partial Prefetching configurationOfficial documentation
- Lazy loadingOfficial documentation
- Image optimizationOfficial documentation