Skip to content

Commit 49c785f

Browse files
committed
perf: memoize root element lookup to avoid repeated DOM queries
1 parent d9fc9cc commit 49c785f

1 file changed

Lines changed: 5 additions & 4 deletions

File tree

packages/react-drag-drop/src/components/DragDrop/DragDropContainer.tsx

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { useCallback, useEffect, useRef, useState } from 'react';
1+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
22
import * as ReactDOM from 'react-dom';
33
import { css } from '@patternfly/react-styles';
44
import {
@@ -290,7 +290,8 @@ export const DragDropContainer: React.FunctionComponent<DragDropContainerProps>
290290
const dragOverlay = <DragOverlay>{activeId && getDragOverlay()}</DragOverlay>;
291291

292292
// Find the React root element dynamically instead of hardcoding 'root'
293-
const getRootElement = () => {
293+
// Memoized to avoid looking up the root element on every render
294+
const rootElement = useMemo(() => {
294295
// Try common root element IDs
295296
const commonRootIds = ['root', 'app', 'main', '__next'];
296297
for (const id of commonRootIds) {
@@ -301,7 +302,7 @@ export const DragDropContainer: React.FunctionComponent<DragDropContainerProps>
301302
}
302303
// Fallback to document.body if no common root is found
303304
return document.body;
304-
};
305+
}, []); // Empty deps - root element doesn't change after mount
305306

306307
return (
307308
<DndContext
@@ -314,7 +315,7 @@ export const DragDropContainer: React.FunctionComponent<DragDropContainerProps>
314315
{...props}
315316
>
316317
{children}
317-
{canUseDOM ? ReactDOM.createPortal(dragOverlay, getRootElement()) : dragOverlay}
318+
{canUseDOM ? ReactDOM.createPortal(dragOverlay, rootElement) : dragOverlay}
318319
</DndContext>
319320
);
320321
};

0 commit comments

Comments
 (0)