Skip to content

Commit 065f428

Browse files
Remove flushSync usage in ShadowRoot component
Replaces flushSync with a regular setState call when initializing the shadow root. This simplifies the effect and removes unnecessary synchronous state updates.
1 parent 0b9c1e0 commit 065f428

File tree

1 file changed

+14
-20
lines changed

1 file changed

+14
-20
lines changed

src/test/helper_components/shadow_root.tsx

Lines changed: 14 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,28 @@
11
import React, {
22
type FC,
33
type PropsWithChildren,
4-
useLayoutEffect,
5-
useRef,
4+
useCallback,
65
useState,
76
} from "react";
8-
import { createPortal, flushSync } from "react-dom";
7+
import { createPortal } from "react-dom";
98

109
const ShadowRoot: FC<PropsWithChildren> = ({ children }) => {
1110
const [shadowRoot, setShadowRoot] = useState<ShadowRoot | null>(null);
1211

13-
const containerRef = useRef<HTMLDivElement>(null);
14-
const isInitializedRef = useRef(false);
15-
16-
useLayoutEffect(() => {
17-
const container = containerRef.current;
18-
if (isInitializedRef.current || !container) {
19-
return;
20-
}
21-
22-
const root =
23-
container.shadowRoot ?? container.attachShadow({ mode: "open" });
24-
isInitializedRef.current = true;
25-
// Use flushSync to synchronously update state within effect, avoiding cascading renders
26-
// while ensuring the shadow root is available immediately for tests
27-
flushSync(() => setShadowRoot(root));
28-
}, []);
12+
const containerRefCallback = useCallback(
13+
(container: HTMLDivElement | null) => {
14+
if (!container) {
15+
return;
16+
}
17+
const root =
18+
container.shadowRoot ?? container.attachShadow({ mode: "open" });
19+
setShadowRoot(root);
20+
},
21+
[],
22+
);
2923

3024
return (
31-
<div ref={containerRef}>
25+
<div ref={containerRefCallback}>
3226
{shadowRoot && createPortal(children, shadowRoot)}
3327
</div>
3428
);

0 commit comments

Comments
 (0)