Skip to content
Source
Sign inSign up
TanStack/redact

Hydration: a component that suspends via use() under a host element shares its parent's cursor and fails hydration #82

Closedtom-engineering(GitHub profile, opens in a new tab) opened this issue 2 comments

Version: @tanstack/redact 0.2.1. deferHydration is unchanged on main (20f6dd6). Baseline: react and react-dom 19.3.1.

What happens

During the initial hydration, a function component suspends: it calls use() on a pending promise, with no <Suspense> between it and its host parent. Redact then reports a hydration mismatch and client-renders the subtree, discarding the server DOM. This happens even though the content matches. Which mismatch you get depends on the component's siblings:

  • If it's the host's only child: server rendered extra nodes inside <div>
  • If a host sibling follows: expected <span> but found NAV

React 19.3 hydrates both cases without errors and keeps every server node.

We hit this with the Next.js adapter (withRedact, Next 16.4.2). Every product route of a large App Router app re-rendered its whole layout on the client, about 1,400 of 1,950 elements on one page. One symptom was "expected <nav>" inside a next/dynamic sidebar. At that point the sidebar container's cursor had n === null, while its only child was the <nav>, so a shared cursor had already been used up.

Repro

// npm i react@19.3.1 react-dom@19.3.1 jsdom@28 @tanstack/redact@0.2.1
// node repro.mjs                -> Redact
// RUNTIME=react node repro.mjs  -> react-dom (control)
import { JSDOM } from 'jsdom'
import * as React from 'react'
import { renderToString } from 'react-dom/server'

const { window } = new JSDOM('<!doctype html><div id="root"></div>')
Object.assign(globalThis, { window, document: window.document })
for (const k of ['Node', 'Element', 'HTMLElement', 'SVGElement', 'Text', 'Comment', 'Event', 'MutationObserver'])
  globalThis[k] = window[k]

const useReact = process.env.RUNTIME === 'react'
const Client = useReact ? React : await import('@tanstack/redact')
const { hydrateRoot } = useReact ? await import('react-dom/client') : await import('@tanstack/redact/dom-client')

async function check(name, tree) {
  const root = document.getElementById('root')
  root.innerHTML = renderToString(tree(React, true)) // server: real React, as under withRedact
  const before = [...root.querySelectorAll('*')]
  const errors = []
  hydrateRoot(root, tree(Client, false), { onRecoverableError: e => errors.push(e.message) })
  await new Promise(r => setTimeout(r, 100))
  const kept = before.filter(n => root.contains(n)).length
  console.log(`${name}\n  errors: ${JSON.stringify(errors)}\n  server nodes kept: ${kept}/${before.length}\n`)
}

// The server renders the resolved content; the client suspends once, like a
// next/dynamic({ ssr: true }) chunk or an RSC payload that isn't ready yet.
let p
const Suspends = ({ R, server }) => { if (!server) R.use(p); return R.createElement('nav', null, 'nav') }

p = new Promise(r => setTimeout(() => r('ok'), 10))
await check('a. only child of its host', (R, server) =>
  R.createElement('div', null, R.createElement(Suspends, { R, server })))

p = new Promise(r => setTimeout(() => r('ok'), 10))
await check('b. host sibling after it', (R, server) =>
  R.createElement('div', null, R.createElement(Suspends, { R, server }), R.createElement('span', null, 'after')))
# Redact 0.2.1 (NODE_ENV=development; production reports only "Hydration mismatch.")
a. only child of its host
  errors: ["Hydration mismatch: server rendered extra nodes inside <div>."]
  server nodes kept: 0/2
b. host sibling after it
  errors: ["Hydration mismatch: expected <span> but found NAV."]
  server nodes kept: 0/3

# react-dom 19.3.1
a. only child of its host
  errors: []
  server nodes kept: 2/2
b. host sibling after it
  errors: []
  server nodes kept: 3/3

Cause

deferHydration (src/dom/features/hydration/full.ts) already describes the hazard:

// Until the initial tree commits, a suspended component's host range is
// unknown. Stop the pass instead of sharing its cursor with later siblings.
const hostParent = findHostParent(fiber);
if (restartInitial && (currentRoot.r.m === null || currentRoot.ri) || hostParent.t === FiberTag.Root)
    throw thenable;
const inheritedCursor = getHydrationCursor(hostParent);
if (inheritedCursor)
    setHydrationCursor(fiber, inheritedCursor);

renderLazy passes restartInitial = true, so a suspending lazy stops the pass, and hydrateRootImpl retries it, which works. renderFunction in src/dom/reconcile.ts calls deferHydration(fiber, e) without the flag. So unless the host parent is the root, a component suspending via use() gets its parent's cursor, the same object rather than a snapshot. Hydration then continues, and the next sibling, or finishHydration on the parent, consumes or rejects the deferred component's server nodes.

The existing coverage misses this shape:

  • tests/rsc-hydration-adopt.test.tsx, "use(promise) suspends during hydration (wrapped pattern)", puts a <Suspense> between the host and the suspending component.
  • tests/next-document-hydration.test.tsx, "retries an initial use(promise) before claiming the document shell", suspends at the document root, which takes the hostParent.t === FiberTag.Root branch.

Neither has a suspending function component directly under a host element.

Possible fix

Treat a suspending function component like lazy during the initial hydration:

 // src/dom/reconcile.ts, renderFunction
-      if (!deferHydration(fiber, e))
+      if (!deferHydration(fiber, e, true))
         handleSuspended(fiber, e);

Applied to the published dist/dom/reconcile.js, this one change makes both repro cases report no errors and keep every server node. I haven't run Redact's own test suite with it, so the after-commit path (currentRoot.r.m !== null) and class components (features/class) may need the same treatment or a separate look.

  1. We hit this in a TanStack Start app (@tanstack/react-start 1.169, Nitro, Vite 8, redact() with the default full preset). The symptom is worse than a client re-render: the content is lost.

    Setup. Docs pages built with fumadocs. The page component calls use(page.data.load()) while hydrating. load() is cached and tags its promise with status/value, but nothing has called it on the client before hydration, so it's still pending. No <Suspense> sits between that component and its host parent. The nearest boundary is the router's, several levels up.

    What happens on a hard load, production build:

    • The server HTML is complete.
    • After hydration, the router boundary's host contains only <!--$0--><!--/$-->. The page body is gone and never renders again, even after the promise resolves.
    • Nothing is logged to the console.
    • Navigating to the same page client-side works. So does a hard load on react-dom 19.3.1.

    Proposed fix confirmed. Changing deferHydration2(fiber, e) to deferHydration2(fiber, e, true) in renderFunction (published dist/dom/reconcile.js, 0.2.1) fixes it. Every docs page then hydrates with its content.

    Workaround on our side. Wrapping the suspending component in a <Suspense> of its own, which is the pattern the existing tests cover.

  2. Thanks for the detailed reproduction and the TanStack Start follow-up. Preserving server DOM when a component suspends during hydration was fixed in #95, released in 0.2.2. I'm closing this as fixed, but please reopen it or share a fresh reproduction if content still disappears or matching server nodes are replaced on 0.2.3.

    AI review notes: The reported hydration patterns were covered by independent node-identity and retry checks. The original full Next.js and TanStack Start applications were not rerun.

  3. tannerlinsley closed this

Sign in to join this conversation.