Diagnose and repair hydration
Reproduce mismatches, identify the first divergent input and repair deterministic initial rendering without hiding meaningful errors.
What you will be able to do
- State the equality requirement for server markup and the first client render.
- Diagnose time, storage, HTML structure and environment-dependent differences.
- Choose a narrow repair and verify it in a real browser.
Hydration starts from an agreement
The server produced markup before the browser attached interactive behavior. During hydration, the client’s first render must describe compatible content and structure. If the server says one value and the first client render says another, React cannot safely assume that attaching behavior to the existing DOM is correct. Hydration warnings therefore report a broken agreement, not merely an aesthetic console issue.
Look for the earliest input that differs. A date calculated independently in two environments can cross a time boundary. Locale and timezone can format the same instant differently. Browser storage exists only in the browser. Random values and environment branches can produce different trees. Invalid HTML can be repaired by the browser parser before React sees it, causing a mismatch even when the source JSX looks superficially consistent.
Use one deterministic initial snapshot
For a timestamp, send one server-produced ISO string and render that same string initially on both sides. If localized presentation is needed, enhance it after hydration. For a stored preference, either supply an authoritative initial value from a request-readable source such as a validated cookie or deliberately show a stable initial state before reading browser storage. Each strategy has user-experience tradeoffs, including a possible visible change.
Do not evaluate typeof window during rendering to choose different markup on the server and first browser pass. That check knows which environment it is in, which is precisely why it can create divergent trees. The example keeps the initial text equal and performs optional localization in an Effect. The server must pass a valid ISO value; the component does not invent separate timestamps for each environment.
Client module
'use client';
import { useEffect, useState } from 'react';
export default function LocalTime({ iso }: { iso: string }) {
const [label, setLabel] = useState(iso);
useEffect(() => {
setLabel(new Intl.DateTimeFormat(undefined, {
dateStyle: 'medium', timeStyle: 'short'
}).format(new Date(iso)));
}, [iso]);
return <time dateTime={iso}>{label}</time>;
}Hydrate authentication from a verified server snapshot
Authentication adds a trust boundary to the rendering problem. A request cookie can let the server establish the current session before rendering. Verify the cookie using the actual session mechanism, then pass only a minimal public session view to the client provider. The server HTML and first client render should use that same public snapshot. Do not pass the signed token, encryption material or an entire account record just to initialize a greeting.
A localStorage value saying signedIn=true is only browser-controlled data. Reading it before the first client render can disagree with the server, and accepting it as authorization would be a separate security defect. Reading a cosmetic preference after mount can be reasonable; granting access from an unverified storage flag is not. Stateless signed or encrypted cookies can persist a session without a per-session database row, but integrity, expiry, cookie attributes and revocation tradeoffs still require a real server design.
The provider below uses the supplied session prop directly instead of copying it once into useState. When new server output supplies a changed session, the view follows it. For logout, clear or expire the actual session on the server, reconcile client query data, and request fresh route output as appropriate. A stale greeting after logout is a synchronization bug; the server must already reject protected actions regardless of what the old client UI displays.
Client module
'use client';
import { createContext, useContext, type ReactNode } from 'react';
type PublicSession = { userId: string; displayName: string } | null;
const SessionContext = createContext<PublicSession>(null);
export function SessionViewProvider({ session, children }: {
session: PublicSession;
children: ReactNode;
}) {
return <SessionContext.Provider value={session}>{children}</SessionContext.Provider>;
}
export function SessionGreeting() {
const session = useContext(SessionContext);
return <p>{session ? `Hello, ${session.displayName}` : 'Signed out'}</p>;
}Keep external-store snapshots and IDs stable
A persisted external store has two initialization moments: the snapshot used to produce server HTML and the snapshot read in the browser. With useSyncExternalStore, provide a getServerSnapshot value that is consistent with what the client uses during hydration, then let the subscribed browser snapshot represent later changes. For object-valued snapshots, return a stable cached snapshot until the store changes; creating a fresh object on every read can cause unnecessary or repeated updates. Consult the store’s SSR integration rather than assuming persistence middleware handles this automatically.
Generated DOM IDs need the same structural discipline. React useId can connect a label to an input across server rendering and hydration when the corresponding component tree agrees. Random numbers or a global counter can depend on different execution order. useId is for accessibility relationships, not a substitute for stable data keys in a list. Changing the tree between environments can still break the assumptions behind generated IDs.
Test the combinations that expose these bugs: a returning user with stored preferences, a signed-out server response while old browser cache remains, a different locale or timezone, and a widget imported from a browser-only library. For the last case, isolate the widget behind a narrow client boundary and consider ssr:false only when that widget cannot render on the server. Keep the meaningful page content and authoritative session decision on their intended side of the boundary.
Check structure before adding escape hatches
Inspect nesting as well as text. A button inside a button or a block element inside an invalid paragraph context can produce a different parsed DOM. Verify generated IDs and form label associations, inspect third-party components, and try a clean browser context to rule out extensions changing markup. A minimal reproduction should keep only the smallest component and input that still diverge.
suppressHydrationWarning is a narrow escape hatch for intentionally unavoidable differences, not a repair for arbitrary tree mismatch. Disabling server rendering for a genuinely browser-only widget can be appropriate, but it removes its initial server-rendered content and changes loading behavior. In Next.js, place an ssr:false dynamic import in an appropriate Client Component. Do not disable rendering for the entire page to conceal an unexplained input error.
Compare observations before and after the change
Use a production build and a fresh browser context. Capture the server response, the initial client assumptions and console warnings. Change one source of nondeterminism at a time, then repeat direct visits and internal navigation. Test with an existing stored preference and without one, and with a different timezone or locale where relevant. A fix tested only in one empty storage state can fail for returning users.
The kata performs structural comparison of two JSON snapshots and reports paths that differ. It teaches you to locate the first divergent value and distinguish missing from present data. It does not reproduce React hydration, HTML parsing or recovery. The /hydration lab supplies the real framework boundary where you must observe warnings and an interactive control after the repair.
Misconceptions to replace
Compare the tempting shortcut with the model you can verify in code.
- CLAIM TO CHALLENGEA localStorage signedIn flag is a database-free authentication system.
- A more accurate model
A browser flag is user-controlled presentation data. Database-free session persistence requires a real server-verified token or cookie design with integrity, expiry and revocation tradeoffs.
- How to check it
N19 and N20 establish server authorization; the session-snapshot section distinguishes verified cookies from browser storage.
- CLAIM TO CHALLENGEuseId, suppressHydrationWarning or ssr:false can repair any hydration problem interchangeably.
- A more accurate model
useId supports stable accessibility relationships in matching trees; suppression is a narrow escape hatch; client-only rendering changes delivery for a specific widget. First identify the actual divergence.
- How to check it
R09 documents useId, R08 documents store snapshots, and N07/N08 describe hydration agreement and escape-hatch limits.
Mistakes to catch in your own code
- A clean screenshot can still contain a hydration warning and recovered client render.
- Do not generate independent initial timestamps, random values or storage-derived markup.
- Warning suppression cannot validate arbitrary structural differences.
Write it by hand
JavaScript logic playground
Locate differences between initial snapshots
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.
- Implement solve({server,client}) for JSON-compatible values. Return sorted paths where leaf values or container types differ, beginning at $. Object keys are simple identifiers.
- Object key order is irrelevant. If a key or array position exists on only one side, report its path. If container types differ, report that container path once rather than descending.
- This compares data snapshots, not HTML or the React hydration algorithm.
Tab moves to the next control. Use spaces to indent and return your answer from solve. Console output is not retained.
Inspect 5 test cases
- Order does not change an object
Input
{ "server": { "title": "Cart", "count": 2 }, "client": { "count": 2, "title": "Cart" } }Expected
[]
- Locale and storage differences
Input
{ "server": { "theme": "light", "time": "10:00" }, "client": { "theme": "dark", "time": "15:30" } }Expected
[ "$.theme", "$.time" ]
- Missing differs from null
Input
{ "server": { "user": null }, "client": {} }Expected
[ "$.user" ]
- Nested and appended item
Input
{ "server": { "items": [ { "id": "a", "qty": 1 } ] }, "client": { "items": [ { "id": "a", "qty": 2 }, { "id": "b", "qty": 1 } ] } }Expected
[ "$.items[0].qty", "$.items[1]" ]
- Container type mismatch
Input
{ "server": { "items": [] }, "client": { "items": {} } }Expected
[ "$.items" ]
Reveal the worked solution and reasoning
function solve(input) {
const mismatches = [];
const kind = value => value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
function compare(left, right, path) {
if (kind(left) !== kind(right)) { mismatches.push(path); return; }
if (Array.isArray(left)) {
for (let index = 0; index < Math.max(left.length, right.length); index++) {
const next = `${path}[${index}]`;
if (index >= left.length || index >= right.length) mismatches.push(next);
else compare(left[index], right[index], next);
}
} else if (left !== null && typeof left === 'object') {
const keys = Array.from(new Set([...Object.keys(left), ...Object.keys(right)])).sort();
for (const key of keys) {
const next = `${path}.${key}`;
if (!Object.hasOwn(left, key) || !Object.hasOwn(right, key)) mismatches.push(next);
else compare(left[key], right[key], next);
}
} else if (left !== right) mismatches.push(path);
}
compare(input.server, input.client, '$');
return mismatches.sort();
}Structural comparison separates a missing field from a field explicitly set to null and ignores irrelevant object insertion order.
A real hydration failure also depends on DOM structure and React behavior, so the snapshot result is a diagnostic aid only.
Verify it in a real Next.js application
Next.js application lab
Repair initial rendering and synchronize a verified session
Open the local application route /hydration after starting the workbench. Follow the experiment and collect the evidence described below.
Make the change
- Inspect the deterministic ISO prop, useId label association and post-mount preference restoration in components/hydration-client.tsx. Compare the response text with the first render and later locale formatting.
- In an isolated copy, introduce one mismatch at a time: independently computed time, a browser-storage-based initial branch or invalid paragraph nesting. For a storage branch, guard browser access so you can distinguish a mismatch from a server ReferenceError.
- Restore the working implementation, save a reading preference and test a direct production-mode reload. Confirm both the absence of hydration diagnostics and a working interactive control.
- Visit /login, choose the opaque session, then open /session. Trace the verified cookie through currentUser into the minimal public props of SessionSnapshot. Sign out in another tab and use Refresh server snapshot here.
- Repeat with the signed session and read its expiry/replay explanation. Compare ordinary logout with explicitly restoring a copied local practice cookie before expiry; do not mistake browser cookie deletion for server-side stateless-token revocation.
Check the behavior
- The repaired hydration route has a meaningful initial snapshot and no mismatch in the observed scenario.
- The saved preference is restored after hydration and the select still works.
- The /session region initially agrees with the verified public server snapshot and updates after a refresh from the other-tab logout.
- Protected requests reject the removed opaque session even if an old client label is still visible.
- A copied unexpired stateless token behaves as documented; client context and localStorage never supply authorization.
Review the application reasoning
The authenticated snapshot is displayed in /session, not in the shared site header. Its provider derives from fresh props rather than freezing the first value in useState.
The broken variants are manual experiments to remove afterward. A passing JSON comparator cannot replace real hydration diagnostics, interaction checks and server authorization tests.
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 causes a hydration mismatch?
The server markup and the first client render disagree in content or structure. I compare their inputs and the parsed DOM, looking for time, locale, randomness, browser-only data or invalid nesting. I then make the initial render deterministic instead of treating suppression as the default answer.
Follow-up questions
- Why can invalid HTML trigger it?
- Why is typeof window inside JSX risky?
- Hydration error diagnosisOfficial documentation
- React hydrateRootOfficial documentation
02How would you initialize a theme stored in localStorage?
I first choose the product tradeoff. A request-readable initial preference can let the server and client agree immediately. Otherwise I render a stable initial value and read storage after hydration, accepting and managing a possible visual change. A browser-only lazy initializer can disagree with the server and must not be assumed safe merely because it runs once.
Follow-up questions
- How would you avoid a visible theme flash?
- What happens if storage access throws?
- Hydration error diagnosisOfficial documentation
- React hydrateRootOfficial documentation
03When is suppressHydrationWarning appropriate?
Only as a deliberate narrow escape hatch for a known unavoidable difference, with its limited behavior understood. It is not a solution for invalid nesting, inconsistent state or an entire mismatched subtree. I first explain why the difference exists and why a deterministic snapshot or client enhancement is not the better design.
Follow-up questions
- What does it fail to fix?
- How would you prove the rest of the component hydrates correctly?
- Hydration error diagnosisOfficial documentation
- React hydrateRootOfficial documentation
04How do you test a hydration repair?
I run a production build, capture browser console errors on a direct visit and verify a real interaction afterward. I include the relevant environment variations, such as a stored preference or timezone. Snapshot comparison can support diagnosis, but only a real browser with server-generated HTML checks the actual hydration path.
Follow-up questions
- Why is a client-only component test insufficient?
- What should happen during a slow script download?
- Hydration error diagnosisOfficial documentation
- Playwright with Next.jsOfficial documentation
05How should an authenticated header hydrate?
The server verifies its session cookie and produces a minimal public session snapshot. The header’s first client render uses the same snapshot, so its content agrees with the HTML. Browser storage cannot establish trusted identity. After login or logout, I update the actual server session and reconcile the client view; protected endpoints remain authoritative even if a stale header is still visible.
Follow-up questions
- Can this work with signed cookies and no per-session database row?
- Why can useState(initialSession) become stale after router.refresh?
- Data securityOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
- React hydrateRootOfficial documentation
06How do persisted stores avoid hydration mismatches?
I establish a deterministic server snapshot and ensure the client uses that value during hydration. With useSyncExternalStore, getServerSnapshot expresses that initial contract while getSnapshot and subscription handle later browser updates. I verify the store’s SSR integration, stable snapshot identity and initialization order instead of assuming that reading localStorage immediately is safe.
Follow-up questions
- Why must object snapshots be cached until they change?
- How do you test a returning user rather than only empty storage?
- React: useSyncExternalStoreOfficial documentation
- Hydration error diagnosisOfficial documentation
- React: synchronizing with effectsOfficial 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
- Hydration error diagnosisOfficial documentation
- React hydrateRootOfficial documentation
- Playwright with Next.jsOfficial documentation
- GreatFrontEnd Next.js interview questionsPublisher practice bank
- Data securityOfficial documentation
- Authentication with Cache ComponentsOfficial documentation
- React: synchronizing with effectsOfficial documentation
- React: useSyncExternalStoreOfficial documentation
- React: useIdOfficial documentation