Skip to content

Don't clone zeroed out display: none subtrees on every layout pass - #2055

Merged
intergalacticspacehighway merged 2 commits into
react:mainfrom
shubh73:skip-recloning-zeroed-display-none
Nov 2, 2026
Merged

intergalacticspacehighway merged 2 commits into
react:mainfrom
shubh73:skip-recloning-zeroed-display-none

Conversation

@shubh73

@shubh73 shubh73 commented Oct 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

zeroOutLayoutRecursively runs for every display: none child on every layout pass of its parent, and calls cloneChildrenIfNeeded() at every level of the hidden subtree. When that subtree is shared with an earlier tree, the clone callback fires for every hidden node on every pass, even though zeroing it out again changes nothing.

In React Native each of those callbacks is a ShadowNode clone, and Fabric's layout() doesn't descend into display: none, so nothing settles them. Every commit that lays out the parent of a hidden view clones everything under it again. Apps that keep screens mounted with display: none, e.g. under <Activity mode="hidden">, pay this on every update for every hidden screen.

This skips cloning and recursing into children whose subtree is already zeroed out: hasNewLayout is set and the layout equals a zeroed out LayoutResults, all the way down. Children are only cloned once one of them needs zeroing out, e.g. after a node was added inside a hidden subtree. Layout results are unchanged.

configVersion is ignored in that comparison. It only validates the layout cache, which is empty after zeroing out, and embedders set it again when they give a cloned node a config. React Native does this for every clone, so without it the check would never match there.

Some notes for review:

  • LayoutResults::operator== skips the generation-tagged caches, computedAutoMinMainSize and the raw dimensions. That's fine here: laying out or measuring a node writes fields it does compare (cachedLayout, the cached measurements), so a node only matches if nothing has laid it out since it was zeroed out.
  • The fast path relies on the embedder leaving hasNewLayout set under display: none nodes, as React Native does. An embedder that clears it (relayout_clones_display_none_subtree_without_new_layout) gets the old behaviour.
  • Skipped children keep their owner from the earlier tree.
  • cloneChildrenIfNeeded still eagerly clones display: contents children of a cloned node, so those are cloned one level down. Anything deeper isn't.

React Native side: react/react-native#59706, which adds a Fantom test on top of this.

Changelog: [General][Fixed] - Fix display: none subtrees being cloned on every layout pass of their parent

Metrics

OPPO CPH2667 (Android 16), React Native RNTester release build, with one visible screen and N hidden display: none screens of about 500 nodes each. Each value is the extra time per update to the visible screen compared with N = 0, as the median of three alternating rounds of 500 updates. The range across rounds is in brackets.

stock this change
Resize, N = 3 +4.1 ms (3.6–5.0) +1.8 ms (1.4–3.3)
Resize, N = 5 +5.9 ms (5.7–7.1) +3.6 ms (3.0–4.1)
Resize, N = 10 +13.0 ms (11.4–14.2) +5.9 ms (5.7–6.4)
Colour change only, N = 10 +6.1 ms (4.6–6.1) +2.9 ms (2.8–3.1)

What's left is mostly in React Native, outside Yoga.

Test plan

Added six tests to tests/YGPersistentNodeCloningTest.cpp, using its clone callback harness:

  • relayout_does_not_clone_zeroed_out_display_none_subtree
  • adding_node_to_display_none_subtree_does_not_clone_zeroed_out_subtrees
  • relayout_does_not_clone_display_contents_in_display_none_subtree
  • relayout_does_not_clone_display_none_subtree_after_config_is_reapplied: clones part of a hidden subtree and calls YGNodeSetConfig on each clone, as React Native does.
  • showing_display_none_subtree_matches_never_hidden_layout
  • relayout_clones_display_none_subtree_without_new_layout

Without the change in CalculateLayout.cpp, the first four fail and the last two pass.

  • ./yogatests: 877 tests pass on main. With this change, all 883 pass. With only the tests, 879 pass and those 4 fail. I built with CXXFLAGS=-Wno-error=character-conversion, because googletest 1.12.1 doesn't build under -Werror with Apple clang 21 (gtest-printers.h).
  • yarn format-check-cpp and yarn lint pass.

🤖 Generated with Claude Code

@meta-cla meta-cla Bot added the CLA Signed label Oct 31, 2026
@facebook-github-tools facebook-github-tools Bot added the Shared with Meta Applied via automation to indicate that an Issue or Pull Request has been shared with the team. label Oct 31, 2026
zeroOutLayoutRecursively runs for every display: none child on every
layout pass of its parent, and called cloneChildrenIfNeeded() at every
level of the hidden subtree. When the subtree is shared with an earlier
tree, the clone callback fired for every hidden node on every pass, even
though zeroing it out again changed nothing. In React Native each of
those callbacks is a ShadowNode clone.

Skip cloning and recursing into children whose subtree is already zeroed
out. configVersion is ignored in that check: it only validates the
layout cache, which is empty after zeroing out, and embedders such as
React Native set it again when they give a cloned node its config.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@shubh73
shubh73 force-pushed the skip-recloning-zeroed-display-none branch from 41c43d5 to 8f6d015 Compare October 31, 2026 02:10
shubh73 added a commit to shubh73/react-native that referenced this pull request Oct 31, 2026
Tests that a hidden subtree isn't cloned on every commit that lays out
its parent, through React commits and setNativeProps, and that hidden
screens lay out the same as never-hidden ones once shown again.

The second test depends on react/yoga#2055 and fails until that change
is synced into the vendored copy of Yoga.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@jamonholmgren

Copy link
Copy Markdown
Contributor

Probably related, although I don't think they're duplicates? react/react-native#59302

@intergalacticspacehighway intergalacticspacehighway left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thanks!
One optional suggestion (for follow-up as it's unrelated): zeroOutLayoutRecursively could clone only the child it writes to e.g. cloneChildIfNeeded(i), not all unowned children. That removes the didCloneChildren flag, and the adding_node_to_display_none_subtree test then expects no clones.

Patch
diff --git a/tests/YGPersistentNodeCloningTest.cpp b/tests/YGPersistentNodeCloningTest.cpp
index 47936bc..8bf2c05 100644
--- a/tests/YGPersistentNodeCloningTest.cpp
+++ b/tests/YGPersistentNodeCloningTest.cpp
@@ -358,8 +358,9 @@ TEST_F(
       std::make_shared<NodeWrapper>(*root, std::vector{hiddenPrime});
 
   std::vector<NodeWrapper*> nodesCloned;
-  // We should only need to clone the shared siblings on the path to "New",
-  // "C" and "D", but not the zeroed out subtree of "D"
+  // Only "New" needs zeroing out, and its ancestors are new revisions that own
+  // it. The shared siblings on its path, "C" and "D", are already zeroed out,
+  // so nothing should be cloned
   onClone = [&](YGNodeConstRef oldNode,
                 YGNodeConstRef /*owner*/,
                 size_t /*childIndex*/) {
@@ -369,7 +370,7 @@ TEST_F(
   YGNodeCalculateLayout(
       rootPrime->node, YGUndefined, YGUndefined, YGDirectionLTR);
 
-  EXPECT_EQ(nodesCloned, (std::vector<NodeWrapper*>{d.get(), c.get()}));
+  EXPECT_TRUE(nodesCloned.empty());
   expectZeroedOut(newNode->node);
   expectZeroedOut(e->node);
 }
diff --git a/yoga/algorithm/CalculateLayout.cpp b/yoga/algorithm/CalculateLayout.cpp
index 32cd9c4..30ec5db 100644
--- a/yoga/algorithm/CalculateLayout.cpp
+++ b/yoga/algorithm/CalculateLayout.cpp
@@ -693,19 +693,15 @@ void zeroOutLayoutRecursively(yoga::Node* const node) {
   // A display: none subtree is zeroed out on every layout pass of its parent.
   // Most of it is usually still zeroed out from an earlier pass, but owned by
   // an earlier tree, so cloning it to zero it out again changes nothing. Only
-  // clone the children, and recurse, when part of the subtree needs it.
+  // clone and recurse into the children whose subtree needs it.
   //
   // This relies on the embedder leaving `hasNewLayout` set under display: none
   // nodes. Children that are skipped keep their owner from the earlier tree.
-  bool didCloneChildren = false;
   for (size_t i = 0; i < node->getChildCount(); i++) {
     if (isLayoutZeroedOutRecursively(node->getChild(i))) {
       continue;
     }
-    if (!didCloneChildren) {
-      node->cloneChildrenIfNeeded();
-      didCloneChildren = true;
-    }
+    node->cloneChildIfNeeded(i);
     zeroOutLayoutRecursively(node->getChild(i));
   }
 }
diff --git a/yoga/node/Node.cpp b/yoga/node/Node.cpp
index 161c190..2cbe841 100644
--- a/yoga/node/Node.cpp
+++ b/yoga/node/Node.cpp
@@ -418,22 +418,26 @@ void Node::clearChildren() {
 // Other Methods
 
 void Node::cloneChildrenIfNeeded() {
-  size_t i = 0;
-  for (Node*& child : children_) {
-    if (child->getOwner() != this) {
-      child = resolveRef(config_->cloneNode(child, this, i));
-      child->setOwner(this);
+  for (size_t i = 0; i < children_.size(); i++) {
+    cloneChildIfNeeded(i);
+  }
+}
 
-      if (child->style().display() == Display::Contents) [[unlikely]] {
-        // The contents node's children are treated as children of the
-        // contents node's parent for layout purposes, so they need
-        // to be cloned as well.
-        child->cloneChildrenIfNeeded();
-      } else if (child->hasContentsChildren()) [[unlikely]] {
-        child->cloneContentsChildrenIfNeeded();
-      }
-    }
-    i += 1;
+void Node::cloneChildIfNeeded(size_t index) {
+  Node*& child = children_[index];
+  if (child->getOwner() == this) {
+    return;
+  }
+  child = resolveRef(config_->cloneNode(child, this, index));
+  child->setOwner(this);
+
+  if (child->style().display() == Display::Contents) [[unlikely]] {
+    // The contents node's children are treated as children of the
+    // contents node's parent for layout purposes, so they need
+    // to be cloned as well.
+    child->cloneChildrenIfNeeded();
+  } else if (child->hasContentsChildren()) [[unlikely]] {
+    child->cloneContentsChildrenIfNeeded();
   }
 }
 
diff --git a/yoga/node/Node.h b/yoga/node/Node.h
index 74fd2c2..72b3d49 100644
--- a/yoga/node/Node.h
+++ b/yoga/node/Node.h
@@ -317,6 +317,7 @@ class YG_EXPORT Node : public ::YGNode {
   void removeChild(size_t index);
 
   void cloneChildrenIfNeeded();
+  void cloneChildIfNeeded(size_t index);
   void cloneContentsChildrenIfNeeded();
   void markDirtyAndPropagate();
   float resolveFlexGrow() const;

@intergalacticspacehighway

intergalacticspacehighway commented Nov 2, 2026 •

Copy link
Copy Markdown
Collaborator

Probably related, although I don't think they're duplicates? react/react-native#59302

yeah not duplicates. RN PR prevents the clones it makes during commit in adoptYogaChild, and this one skips the clones Yoga makes when it zeroes out an already-zeroed display: none subtree so somewhat related when it comes to prevent cloning 😅.

@intergalacticspacehighway
intergalacticspacehighway merged commit 0747590 into react:main Nov 2, 2026
33 checks passed
intergalacticspacehighway added a commit that referenced this pull request Nov 2, 2026
Follow-up to #2055, from review. `zeroOutLayoutRecursively` cloned all of a
node's unowned children as soon as one of them needed zeroing out. It now
clones only that child, through a new `Node::cloneChildIfNeeded(index)` that
`cloneChildrenIfNeeded` also uses.

Co-authored-by: nishan <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
meta-codesync Bot pushed a commit to react/react-native that referenced this pull request Nov 17, 2026
Summary:
**The Bug**

Showing a subtree hidden with `<Activity mode="hidden">` again can abort debug builds with `Attempt to mutate a sealed object`. Release builds have no assertion, so the same layout pass silently changes shadow nodes that the committed tree still uses.

**The Cause**

React keeps the instance of a hidden host component, commits a `display: none` clone of it that shares its children, and appends the instance (or a clone of it) again when the subtree is shown. Since react/yoga#2055, zeroing out a `display: none` subtree no longer clones children that are already zeroed out, so the committed tree can share children that the kept instance owns. The instance itself is unowned, so appending it adopts it in place, and its layout treats the shared children as its own.

**The Fix**

Cloning an unowned `YogaLayoutableShadowNode` points the owner of the children it owns at the detached-owner sentinel, through `updateYogaChildrenOwnersIfNeeded`, which now takes the Yoga node to update. Whichever node lays those children out next (the kept instance or any clone of it) clones them first through the Yoga clone callback.

The kept instance's stale layout cache is already handled by comparing each new child's layout results in `updateYogaChildren`. react/yoga#2055's optimization stays in place.

Changelog:
[General][Fixed] - Fix showing a subtree hidden with `<Activity>` laying out shadow nodes in place that the committed tree still uses, which crashed debug builds

Reviewed By: lenaic

Differential Revision: D132556429

Pull Request resolved: #60082
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed Shared with Meta Applied via automation to indicate that an Issue or Pull Request has been shared with the team.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants