@@ -14,13 +14,41 @@ export default function useHeights<T>(
14
14
const [ updatedMark , setUpdatedMark ] = React . useState ( 0 ) ;
15
15
const instanceRef = useRef ( new Map < React . Key , HTMLElement > ( ) ) ;
16
16
const heightsRef = useRef ( new CacheMap ( ) ) ;
17
+ const heightUpdateIdRef = useRef ( 0 ) ;
18
+
19
+ function collectHeight ( ) {
20
+ heightUpdateIdRef . current += 1 ;
21
+ const currentId = heightUpdateIdRef . current ;
22
+
23
+ Promise . resolve ( ) . then ( ( ) => {
24
+ // Only collect when it's latest call
25
+ if ( currentId !== heightUpdateIdRef . current ) return ;
26
+
27
+ let changed = false ;
28
+
29
+ instanceRef . current . forEach ( ( element , key ) => {
30
+ if ( element && element . offsetParent ) {
31
+ const htmlElement = findDOMNode < HTMLElement > ( element ) ;
32
+ const { offsetHeight } = htmlElement ;
33
+ if ( heightsRef . current . get ( key ) !== offsetHeight ) {
34
+ changed = true ;
35
+ heightsRef . current . set ( key , htmlElement . offsetHeight ) ;
36
+ }
37
+ }
38
+ } ) ;
39
+ if ( changed ) {
40
+ setUpdatedMark ( c => c + 1 ) ;
41
+ }
42
+ } ) ;
43
+ }
17
44
18
45
function setInstanceRef ( item : T , instance : HTMLElement ) {
19
46
const key = getKey ( item ) ;
20
47
const origin = instanceRef . current . get ( key ) ;
21
48
22
49
if ( instance ) {
23
50
instanceRef . current . set ( key , instance ) ;
51
+ collectHeight ( ) ;
24
52
} else {
25
53
instanceRef . current . delete ( key ) ;
26
54
}
@@ -35,23 +63,5 @@ export default function useHeights<T>(
35
63
}
36
64
}
37
65
38
- function collectHeight ( ) {
39
- let changed = false ;
40
-
41
- instanceRef . current . forEach ( ( element , key ) => {
42
- if ( element && element . offsetParent ) {
43
- const htmlElement = findDOMNode < HTMLElement > ( element ) ;
44
- const { offsetHeight } = htmlElement ;
45
- if ( heightsRef . current . get ( key ) !== offsetHeight ) {
46
- changed = true ;
47
- heightsRef . current . set ( key , htmlElement . offsetHeight ) ;
48
- }
49
- }
50
- } ) ;
51
- if ( changed ) {
52
- setUpdatedMark ( c => c + 1 ) ;
53
- }
54
- }
55
-
56
66
return [ setInstanceRef , collectHeight , heightsRef . current , updatedMark ] ;
57
67
}
0 commit comments