# Autopsy #06: Anatomy of a Hydration Mismatch & Full Subtree Bailout

- **Canonical URL:** https://frontend.rocks/autopsies/hydration-flicker-and-bailout/
- **Case:** #06
- **Failure Mode:** Hydration Desync
- **Production Symptom:** SSR page paints instantly, flickers violently when JS boots, and wipes user input in form fields.
- **Last Verified:** 2026-11-16

## Causal Chain
1. [Streaming SSR & Progressive Flushing](https://frontend.rocks/concepts/streaming-ssr-flushing.md): Server streams HTML chunks early with server-computed timestamps and default filter state before JS loads.
2. [Resumability vs Hydration](https://frontend.rocks/concepts/resumability-vs-hydration.md): Traditional hydration must re-execute the entire component tree on the client to attach event listeners.
3. [Hydration Mismatch & Subtree Bailout Mechanics](https://frontend.rocks/concepts/hydration-mismatch-mechanics.md): A text or attribute mismatch forces the framework to discard the SSR DOM subtree and re-render from scratch.
4. [URL as a State Store](https://frontend.rocks/concepts/url-as-state-store.md): Uncontrolled query-param parsing on the client diverges from server-rendered defaults during initial boot.
5. [Client-Side Router & Radix Tree Matching](https://frontend.rocks/concepts/client-side-router-internals.md): Router reconciliation replaces the bailed-out DOM nodes, destroying focus and typed input in form fields.

## Primary Sources
- https://react.dev/reference/react-dom/client/hydrateRoot
- https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
- https://qwik.dev/docs/concepts/resumable/
- https://web.dev/articles/rendering-on-the-web

---
## Incident Report

A product PR added a "Last updated" local timestamp badge inside the catalog header right above the `<input name="q">` search bar. Local development runs in UTC on a fast workstation showed zero visual glitches.

Within 30 minutes of the deploy, RUM telemetry recorded a sharp CLS regression and mobile search abandonment spike.

- **T+00:00**: Streaming SSR release ships to edge workers.
- **T+10:00**: FCP holds at 320 ms, allowing mobile users to tap and type into `<input name="q">` immediately.
- **T+18:00**: At `t = 1.4 s` when JS finishes hydrating, CLS spikes to 0.28, the filter sidebar jumps, and typed search characters vanish.
- **T+35:00**: Mobile search abandonment rises 9% across non-UTC timezones.

## The Red Herring

The first Slack reflex was to add `suppressHydrationWarning` on the timestamp `<span>` and wrap the search bar in a `useEffect(() => setMounted(true), [])` guard. Local dev console warnings disappeared immediately.

In production, the patch made the outage worse. `mounted` gating rendered the entire search form empty on the server and mounted it late on the client, guaranteeing a 0.28 layout shift on every load while still failing to address URL parameter skew.

## Causal Chain

A hydration wipe is a deterministic cascade across five runtime layers, triggered whenever client boot produces a different virtual tree than the streamed HTML.

1. Streaming SSR flushes the initial HTML shell and interactive `<input>` before JavaScript arrives.
2. Traditional hydration re-executes the full component tree on the main thread to bind listeners.
3. A single non-deterministic value triggers a hydration mismatch and aborts node reuse for the nearest boundary.
4. Reading `window.location` or `URLSearchParams` differently from the server widens the mismatch to the route shell.
5. Client router reconciliation unmounts the SSR DOM nodes and mounts fresh ones, wiping native input state and focus.

## Failure Simulator

Step through the five-stage hydration bailout sequence in the simulator below. Track `userInput` and `bailoutScope` from the initial streaming flush through the router re-mount to see why a tiny timestamp mismatch deletes user keystrokes.

## Layer Dissection

### 01 → 02: Early Streaming Flush Meets Full-Tree Hydration

With [Streaming SSR Flushing](/concepts/streaming-ssr-flushing), the server writes the document shell and `<form>` markup to the HTTP response stream immediately, letting the browser parse and paint the `<input>` in 320 ms.

Because the page uses [Resumability vs Hydration](/concepts/resumability-vs-hydration) under a hydration model, the HTML contains no serialized listener closures. The browser displays inert DOM nodes until the client bundle downloads, parses, and re-executes every component from the root down to attach event handlers.

### 02 → 03: Non-Deterministic Render Triggers Hydration Bailout

During that client walk, [Hydration Mismatch Mechanics](/concepts/hydration-mismatch-mechanics) compare each rendered virtual node against the existing DOM node. When the badge calls `new Date().toLocaleTimeString()`, the client string (`6:02 AM PST`) fails equality against the server string (`14:02 UTC`):

- The runtime throws a hydration mismatch error.
- It discards the DOM subtree up to the nearest `<Suspense>` boundary (or the document root when none exists).
- It falls back to synchronous client-side rendering (CSR) for that entire subtree.

### 03 → 04: URL State Skew Widens the Bailout

The blast radius expands when [URL as State Store](/concepts/url-as-state-store) logic diverges across environments.

On the server, the CDN stripped tracking query parameters and passed a normalized route object without `location.hash`. On the client, a filter hook read `window.location.search` directly during the first render pass, producing a different `sort` state than the SSR payload and invalidating the root layout boundary.

### 04 → 05: Router Reconciliation Destroys Live Form State

Once the bailout reaches the route wrapper, [Client-Side Router Internals](/concepts/client-side-router-internals) reconcile the mismatched branch by unmounting the server-created DOM elements and inserting newly created elements.

Native `<input>` values typed before hydration live only in the browser's DOM node state, not in React state. Replacing the DOM node drops `document.activeElement` back to `document.body` and resets the input value to `""`.

## Architectural Fix & Invariants

```tsx
import { useSyncExternalStore } from 'react';

const emptySubscribe = () => () => {};

export function LocalTimestamp({ iso }: { iso: string }) {
  const formatted = useSyncExternalStore(
    emptySubscribe,
    () => new Date(iso).toLocaleTimeString(),
    () => new Date(iso).toUTCString()
  );

  return <time dateTime={iso}>{formatted}</time>;
}
```

**Architectural Invariants:**
- **Zero browser globals in render**: Never read `window`, `localStorage`, `navigator.language`, or `Date.now()` during initial render; use `useSyncExternalStore` with an explicit server snapshot.
- **Single serialized URL state**: Pass parsed `searchParams` from the server loader as props rather than reading `window.location` independently on the client.
- **Granular `<Suspense>` blast-radius caps**: Wrap volatile subtrees in `<Suspense>` so a hydration bailout never discards ancestor `<form>` or `<input>` elements.
- **No `useEffect` mount-gating above the fold**: Never return `null` on the server to silence a mismatch; doing so converts a mismatch into guaranteed CLS.

**Golden Rule:** A single unguarded mismatch above a `<form>` wipes every pre-hydration keystroke; isolate client-only snapshots with `useSyncExternalStore` and fence volatile subtrees inside `<Suspense>`.
