facebook/react

Bug: Detached Elements Observed When Toggling Content with ReactDOM.createPortal()

suraj-pachakar opened this issue · 0 comments

We observed a possible memory leak when using ReactDOM.createPortal() to render components. The issue occurs when toggling the portal content between a RadioGroup and the text Loading.... If the RadioGroup is interacted with before toggling, some DOM elements are not properly cleaned up, leaving detached nodes in memory.

However, if no interaction happens with the RadioGroup, the content toggles without any memory issues.

React version: 18.3.1

Steps To Reproduce

  1. Visit the JSFiddle example.
  2. Click on the Load Content button to render the RadioGroup.
  3. Interact with the RadioGroup by selecting the Other option. (eg: option B)
  4. Click on the Unload Content button to remove the RadioGroup.
  5. Open the Memory tab in the browser developer tools and trigger Garbage Collection.
  6. Select the Detached Elements profiling type and take a snapshot of the memory to observe detached nodes.

Link to code example: JSFiddle example

The current behavior

Detached elements are present in the memory snapshot after interacting with the RadioGroup and toggling it off. This indicates a potential memory leak caused by ReactDOM.createPortal().
image

The expected behavior

Detached nodes should not be present after toggling the RadioGroup and triggering garbage collection, regardless of interactions.