Skip to content

Bug: hiding an <Activity> after an interrupted render leaves deleted DOM nodes behind #38430

Backlog

Description

@CinchBlue

React version: 19.3.1 and 19.3.0-canary-edae846a-20261125, development and production. Chrome and Firefox.

Steps to reproduce

Save the page below as activity-hide.html and open it. ?v=<version> and &dev pick the build.

  1. Render <Activity><div><Gate/><ul>items</ul></div></Activity> and remove one item, so the <ul> has committed a deletion.
  2. Start a transition. Make it yield inside <Gate>, before React begins the <ul>.
  3. In that gap, hide the <Activity> with an urgent update, then show it.
  4. Reorder and remove items.

Current behaviour

The DOM shows cd; the state holds only d. With a <Suspense> boundary in place of the list, its fallback can stay
on screen beside the content. Nothing is logged. Hiding after the transition has finished behaves correctly.

Expected behaviour

The DOM shows d.

Cause

recursivelyTraverseDisconnectPassiveEffects walks the committed tree and finds a ChildDeletion flag left from an
earlier commit. It calls detachAlternateSiblings, which clears sibling along parentFiber.alternate.child. After an
interrupted render that cloned the parent but did not begin it, alternate.child === parentFiber.child, so the links
being cut are those of the live children.

Proposed fix

activity-hide.patch: skip the detach when both fibers share the child. Includes a test that fails without the change.

Repro page: activity-hide.html
<!doctype html>
<meta charset="utf-8">
<title>React: hiding an Activity after an interrupted render leaves deleted nodes in the DOM</title>
<pre id="log">running...</pre>
<div id="root"></div>
<script type="module">
// ?v=<react version, default 19.3.1>  &dev for the development build
const q = new URLSearchParams(location.search), v = q.get("v") || "19.3.1", dev = q.has("dev") ? "?dev" : "";
const React = (await import(`https://esm.sh/react@${v}${dev}`)).default;
const { createRoot } = (await import(`https://esm.sh/react-dom@${v}/client${dev}`)).default;
const { createElement: h, Activity, useState, startTransition } = React;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function run(interrupt) {
  const set = {};
  let armed = false;
  function click(update) {
    const b = document.body.appendChild(document.createElement("button"));
    b.onclick = update; b.click(); b.remove();
  }
  // Rendered before the list. Once armed, it queues a click and blocks long enough for React to yield.
  function Gate({ n }) {
    if (n && armed) {
      armed = false;
      const channel = new MessageChannel();
      channel.port1.onmessage = () => click(() => set.mode("hidden"));
      channel.port2.postMessage(null);
      for (const end = performance.now() + 30; performance.now() < end; );
    }
    return null;
  }
  function App() {
    const [mode, setMode] = useState("visible");
    const [n, setN] = useState(0);
    const [items, setItems] = useState(["a", "b", "c"]);
    Object.assign(set, { mode: setMode, n: setN, items: setItems });
    return h(Activity, { mode }, h("div", null,
      h(Gate, { n }),
      h("ul", null, items.map((i) => h("li", { key: i }, i)))));
  }
  const root = createRoot(document.getElementById("root"));
  const shown = () => document.getElementById("root").innerText.replace(/\s/g, "");
  root.render(h(App));
  await sleep(300);
  click(() => set.items(["b", "c"]));        // 1. commit one deletion
  await sleep(100);
  armed = interrupt;
  startTransition(() => set.n(1));           // 2. a transition, interrupted by "hide" inside Gate
  await sleep(300);
  if (!interrupt) { click(() => set.mode("hidden")); await sleep(100); }
  click(() => set.mode("visible"));          // 3. show again
  await sleep(300);
  click(() => set.items(["c", "b", "d"]));   // 4. reorder and insert
  await sleep(100);
  click(() => set.items(["d"]));             // 5. keep only "d"
  await sleep(300);
  const text = shown();
  root.unmount();
  return text;
}

const interrupted = await run(true), control = await run(false);
const line = (name, text) => `${name}: DOM shows "${text}", expected "d" -> ${text === "d" ? "ok" : "BUG"}`;
document.getElementById("log").textContent =
  [`react ${React.version}${dev ? " development" : " production"}`,
   line("hide interrupts a transition", interrupted), line("hide after the transition (control)", control)].join("\n");
document.title = "done";
</script>
Proposed fix with tests: activity-hide.patch (against main edae846a9a)
diff --git a/packages/react-reconciler/src/ReactFiberCommitWork.js b/packages/react-reconciler/src/ReactFiberCommitWork.js
index 4fbeec2..eb80fce 100644
--- a/packages/react-reconciler/src/ReactFiberCommitWork.js
+++ b/packages/react-reconciler/src/ReactFiberCommitWork.js
@@ -4911,7 +4911,14 @@ function detachAlternateSiblings(parentFiber: Fiber) {
   // but we can disconnect the `sibling` and `child` pointers.
 
   const previousFiber = parentFiber.alternate;
-  if (previousFiber !== null) {
+  if (
+    previousFiber !== null &&
+    // If both fibers point to the same child, then these are the current
+    // children, not the previous ones. This happens when the alternate was
+    // cloned by a render that was interrupted before it began this fiber, and
+    // this fiber still has a ChildDeletion flag from an earlier commit.
+    previousFiber.child !== parentFiber.child
+  ) {
     let detachedChild = previousFiber.child;
     if (detachedChild !== null) {
       previousFiber.child = null;
diff --git a/packages/react-reconciler/src/__tests__/ReactActivityInterruptedHide-test.js b/packages/react-reconciler/src/__tests__/ReactActivityInterruptedHide-test.js
new file mode 100644
index 0000000..50a056b
--- /dev/null
+++ b/packages/react-reconciler/src/__tests__/ReactActivityInterruptedHide-test.js
@@ -0,0 +1,100 @@
+/**
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @emails react-core
+ * @jest-environment node
+ */
+
+'use strict';
+
+let React;
+let ReactNoop;
+let Scheduler;
+let act;
+let waitFor;
+let assertLog;
+let Activity;
+let useState;
+let startTransition;
+
+describe('Activity hidden after an interrupted render', () => {
+  beforeEach(() => {
+    jest.resetModules();
+
+    React = require('react');
+    ReactNoop = require('react-noop-renderer');
+    Scheduler = require('scheduler');
+    const InternalTestUtils = require('internal-test-utils');
+    act = InternalTestUtils.act;
+    waitFor = InternalTestUtils.waitFor;
+    assertLog = InternalTestUtils.assertLog;
+    Activity = React.Activity;
+    useState = React.useState;
+    startTransition = React.startTransition;
+  });
+
+  it('keeps the child list intact', async () => {
+    let setMode;
+    let setStep;
+    let setItems;
+    function Gate({step}) {
+      Scheduler.log('Gate ' + step);
+      return null;
+    }
+    function App() {
+      const [mode, _setMode] = useState('visible');
+      const [step, _setStep] = useState(0);
+      const [items, _setItems] = useState(['a', 'b', 'c']);
+      setMode = _setMode;
+      setStep = _setStep;
+      setItems = _setItems;
+      return (
+        <Activity mode={mode}>
+          <div>
+            <Gate step={step} />
+            <ul>
+              {items.map(item => (
+                <li key={item} prop={item} />
+              ))}
+            </ul>
+          </div>
+        </Activity>
+      );
+    }
+
+    const root = ReactNoop.createRoot();
+    await act(() => root.render(<App />));
+    assertLog(['Gate 0']);
+    // Commit one deletion inside the list
+    await act(() => setItems(['b', 'c']));
+    assertLog(['Gate 0']);
+
+    // Start a transition and yield before the list is begun
+    startTransition(() => setStep(1));
+    await waitFor(['Gate 1']);
+
+    // Interrupt it by hiding the tree, then show it again
+    await act(() => {
+      ReactNoop.flushSync(() => setMode('hidden'));
+    });
+    Scheduler.unstable_clearLog();
+    await act(() => setMode('visible'));
+    Scheduler.unstable_clearLog();
+
+    await act(() => setItems(['c', 'b', 'd']));
+    Scheduler.unstable_clearLog();
+    await act(() => setItems(['d']));
+    Scheduler.unstable_clearLog();
+
+    expect(root).toMatchRenderedOutput(
+      <div>
+        <ul>
+          <li prop="d" />
+        </ul>
+      </div>,
+    );
+  });
+});

Activity

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