Skip to content

Bug: Fragment ref listeners, observers and reactFragments handles never reach children hydrated after the ref attached (a Suspense or Activity boundary directly inside the Fragment) #38253

Open

Description

@shareapparent

React version: 19.3.1 (react, react-dom), and the same on the newest canary, 19.3.0-canary-df6aa4ec-20261112

Steps To Reproduce

  1. Server-render a Fragment with a ref whose first-level content is a Suspense boundary:

    function App() {
      const attach = (fragment) => {
        if (!fragment) return;
        fragment.addEventListener('ping', () => console.log('heard'));
        fragment.observeUsing(resizeObserver);
      };
      return (
        <main>
          <Fragment ref={attach}>
            <Suspense fallback={null}>
              <p><input id="field" /></p>
            </Suspense>
          </Fragment>
        </main>
      );
    }
  2. hydrateRoot(container, <App />) and wait until the boundary has hydrated (it hydrates in a later pass than the root).

  3. document.getElementById('field').dispatchEvent(new Event('ping', { bubbles: true })).

Link to code example: the self-contained test below (react, react-dom, jsdom 29 and vitest 3 only; its vitest.config.ts sets esbuild: { jsx: 'automatic' } and test: { environment: 'jsdom' }). Each test states the expected behaviour: the two hydrated cases fail, the two controls pass.

fragment-ref-hydration.repro.test.tsx
// @vitest-environment jsdom
// Repro: a Fragment ref's listeners, observers and handles never reach elements hydrated after the ref attached.
// Needs only react, react-dom (19.3.1), jsdom and vitest. Each test states the expected behaviour: the hydrated
// cases fail while the bug is there, the client-rendered control passes.
import { afterEach, expect, it } from 'vitest';
import { Activity, Fragment, Suspense, act, type FragmentInstance, type ReactNode } from 'react';
import { renderToString } from 'react-dom/server';
import { createRoot, hydrateRoot, type Root } from 'react-dom/client';

(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;

let root: Root | null = null;
let container: HTMLElement | null = null;
afterEach(() => {
  act(() => root?.unmount());
  container?.remove();
});

// jsdom has no ResizeObserver; React only calls observe() and unobserve() on the one it is given.
const observerOf = (targets: Element[]) => ({
  observe: (target: Element) => { targets.push(target); },
  unobserve: () => {},
  disconnect: () => {},
}) as unknown as ResizeObserver;

/** Draws `content` under a Fragment whose ref listens and observes, then says what reached the field's <p>. */
async function reach(content: ReactNode, how: 'hydrate' | 'client') {
  let heard = 0;
  let instance: FragmentInstance | null = null;
  const targets: Element[] = [];
  const attach = (fragment: FragmentInstance | null) => {
    if (!fragment) return;
    instance = fragment;
    fragment.addEventListener('ping', () => { heard += 1; });
    fragment.observeUsing(observerOf(targets));
  };
  const app = <main><Fragment ref={attach}>{content}</Fragment></main>;
  container = document.body.appendChild(document.createElement('div'));
  if (how === 'hydrate') {
    container.innerHTML = renderToString(app);
    await act(async () => { root = hydrateRoot(container!, app); });
  } else {
    await act(async () => { root = createRoot(container!); root.render(app); });
  }
  // Everything has hydrated by now: act flushed the boundary's own, later pass.
  const field = document.getElementById('field')!;
  const top = field.parentElement as HTMLElement & { reactFragments?: Set<FragmentInstance> };
  field.dispatchEvent(new Event('ping', { bubbles: true }));
  return { heard, observed: targets.includes(top), handle: top.reactFragments?.has(instance!) === true };
}

const REACHED = { heard: 1, observed: true, handle: true };
const field = <p><input id="field" /></p>;

it('control: client-rendered content under a Suspense boundary is reached', async () => {
  expect(await reach(<Suspense fallback={null}>{field}</Suspense>, 'client')).toEqual(REACHED);
});

it('control: hydrated content with no boundary between it and the Fragment is reached', async () => {
  expect(await reach(field, 'hydrate')).toEqual(REACHED);
});

it('hydrated content under a Suspense boundary is reached', async () => {
  // Fails: { heard: 0, observed: false, handle: false }.
  expect(await reach(<Suspense fallback={null}>{field}</Suspense>, 'hydrate')).toEqual(REACHED);
});

it('hydrated content under an Activity boundary is reached', async () => {
  // Fails the same way.
  expect(await reach(<Activity mode="visible">{field}</Activity>, 'hydrate')).toEqual(REACHED);
});

The current behavior

For the <p> that hydrated inside the boundary:

  • the Fragment's listener never runs (heard is not logged);
  • the observer was never given the element;
  • the element has no reactFragments property.

The same happens with <Activity mode="visible"> in place of the Suspense boundary.

Controls that behave as documented:

  • the same tree rendered with createRoot;
  • hydrated content with no boundary between it and the Fragment;
  • a boundary below a host element (<div><Suspense>…</Suspense></div>): the <div> is the first-level child;
  • a boundary the server left to the client (<!--$!-->): its children are placed, so they are reached.

Children added inside the boundary after it hydrated are reached. The hydrated ones never are, until something hides and shows the boundary again.

The expected behavior

The Fragment reference says a FragmentInstance adds its listeners to children as they are added, and that every first-level DOM child of a Fragment with a ref carries reactFragments. Children that hydrate later are first-level children like any other: they should get the listeners, the observers and the handle once they hydrate.

Likely cause

  • When the ref attaches (commitAttachRef → createFragmentInstance, then addEventListener and observeUsing from the ref callback), each walks the Fragment's hosts with traverseFragmentInstancesAndTextInstances. A dehydrated boundary has no host fibers below it yet, so nothing inside it is visited.
  • When the boundary hydrates (updateDehydratedSuspenseComponent, updateDehydratedActivityComponent in ReactFiberBeginWork.js), its primary children are flagged Hydrating, not Placement.
  • commitNewChildToFragmentInstances (ReactFiberFragmentInstance.js) is only called from the placement path (insertOrAppendPlacementNode and its container form in ReactFiberCommitHostEffects.js), so it never runs for hydrated hosts.
  • commitFragmentInstanceInsertionEffects runs only from the reappear path (recursivelyTraverseReappearLayoutEffects in ReactFiberCommitWork.js), and the boundary was never hidden.
  • Nothing in the hydration commit (commitHostHydratedInstance, commitHydratedSuspenseInstance) tells the Fragment instances above about the hosts it just adopted.

Running the same bookkeeping for hosts as they hydrate (what commitNewChildToFragmentInstance does for a placed host) would close it.

Why it matters

An ancestor has no public signal that a boundary inside its content hydrated: none of its effects, refs or lifecycles run in that commit. So it cannot repair this itself by listening again at the right time, and next/dynamic with a loading state, lazy under its own Suspense and Activity all put a boundary at the top of whatever they are given.

Activity

  1. anish19p-spec commented on Nov 15, 2026

    @anish19p-spec

    Hey, @shareapparent I'd like to work on this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions

      ⌂ Proxy