Skip to content

Commit 4c10294

Browse files
authored
refactor Portal to use useOnUnmount hook (#2458)
1 parent 74c9873 commit 4c10294

File tree

1 file changed

+10
-18
lines changed
  • packages/@headlessui-react/src/components/portal

1 file changed

+10
-18
lines changed

packages/@headlessui-react/src/components/portal/portal.tsx

Lines changed: 10 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,8 @@ import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
1919
import { usePortalRoot } from '../../internal/portal-force-root'
2020
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
2121
import { optionalRef, useSyncRefs } from '../../hooks/use-sync-refs'
22+
import { useOnUnmount } from '../../hooks/use-on-unmount'
2223
import { useOwnerDocument } from '../../hooks/use-owner'
23-
import { microTask } from '../../utils/micro-task'
2424
import { env } from '../../utils/env'
2525

2626
function usePortalTarget(ref: MutableRefObject<HTMLElement | null>): HTMLElement | null {
@@ -90,10 +90,7 @@ function PortalFn<TTag extends ElementType = typeof DEFAULT_PORTAL_TAG>(
9090

9191
let ready = useServerHandoffComplete()
9292

93-
let trulyUnmounted = useRef(false)
9493
useIsoMorphicEffect(() => {
95-
trulyUnmounted.current = false
96-
9794
if (!target || !element) return
9895

9996
// Element already exists in target, always calling target.appendChild(element) will cause a
@@ -102,24 +99,19 @@ function PortalFn<TTag extends ElementType = typeof DEFAULT_PORTAL_TAG>(
10299
element.setAttribute('data-headlessui-portal', '')
103100
target.appendChild(element)
104101
}
102+
}, [target, element])
105103

106-
return () => {
107-
trulyUnmounted.current = true
108-
109-
microTask(() => {
110-
if (!trulyUnmounted.current) return
111-
if (!target || !element) return
104+
useOnUnmount(() => {
105+
if (!target || !element) return
112106

113-
if (element instanceof Node && target.contains(element)) {
114-
target.removeChild(element)
115-
}
107+
if (element instanceof Node && target.contains(element)) {
108+
target.removeChild(element)
109+
}
116110

117-
if (target.childNodes.length <= 0) {
118-
target.parentElement?.removeChild(target)
119-
}
120-
})
111+
if (target.childNodes.length <= 0) {
112+
target.parentElement?.removeChild(target)
121113
}
122-
}, [target, element])
114+
})
123115

124116
if (!ready) return null
125117

0 commit comments

Comments
 (0)