@@ -19,8 +19,8 @@ import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
19
19
import { usePortalRoot } from '../../internal/portal-force-root'
20
20
import { useServerHandoffComplete } from '../../hooks/use-server-handoff-complete'
21
21
import { optionalRef , useSyncRefs } from '../../hooks/use-sync-refs'
22
+ import { useOnUnmount } from '../../hooks/use-on-unmount'
22
23
import { useOwnerDocument } from '../../hooks/use-owner'
23
- import { microTask } from '../../utils/micro-task'
24
24
import { env } from '../../utils/env'
25
25
26
26
function usePortalTarget ( ref : MutableRefObject < HTMLElement | null > ) : HTMLElement | null {
@@ -90,10 +90,7 @@ function PortalFn<TTag extends ElementType = typeof DEFAULT_PORTAL_TAG>(
90
90
91
91
let ready = useServerHandoffComplete ( )
92
92
93
- let trulyUnmounted = useRef ( false )
94
93
useIsoMorphicEffect ( ( ) => {
95
- trulyUnmounted . current = false
96
-
97
94
if ( ! target || ! element ) return
98
95
99
96
// 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>(
102
99
element . setAttribute ( 'data-headlessui-portal' , '' )
103
100
target . appendChild ( element )
104
101
}
102
+ } , [ target , element ] )
105
103
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
112
106
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
+ }
116
110
117
- if ( target . childNodes . length <= 0 ) {
118
- target . parentElement ?. removeChild ( target )
119
- }
120
- } )
111
+ if ( target . childNodes . length <= 0 ) {
112
+ target . parentElement ?. removeChild ( target )
121
113
}
122
- } , [ target , element ] )
114
+ } )
123
115
124
116
if ( ! ready ) return null
125
117
0 commit comments