@@ -2,10 +2,15 @@ import { useCallback, useEffect, useRef, useState } from 'react';
2
2
3
3
export const useSizeMonitor = ( props , container ) => {
4
4
const { height : heightProp , width : widthProp , minHeight, minWidth } = props ;
5
- const [ height , setHeight ] = useState ( null ) ;
6
- const [ width , setWidth ] = useState ( null ) ;
5
+ const [ sizeState , setSizeState ] = useState ( {
6
+ height : null ,
7
+ width : null
8
+ } ) ;
9
+ const observer = useRef ( null ) ;
7
10
8
- const enableSizeMonitor = typeof heightProp === 'string' || typeof widthProp === 'string' ;
11
+ const dynamicHeightProp = typeof heightProp === 'string' ;
12
+ const dynamicWidthProp = typeof heightProp === 'string' ;
13
+ const enableSizeMonitor = dynamicHeightProp || dynamicWidthProp ;
9
14
10
15
const recalculateSize = useCallback (
11
16
( e ?) => {
@@ -20,30 +25,32 @@ export const useSizeMonitor = (props, container) => {
20
25
clientRectWidth = e [ 0 ] . contentRect . width ;
21
26
}
22
27
23
- // console.log(props);
24
-
25
- setHeight ( Math . max ( minHeight , clientRectHeight ) ) ;
26
- setWidth ( Math . max ( minWidth , clientRectWidth ) ) ;
28
+ if ( dynamicHeightProp || dynamicWidthProp ) {
29
+ setSizeState ( ( state ) => ( {
30
+ ...state ,
31
+ ...( dynamicHeightProp && { height : Math . max ( minHeight , clientRectHeight ) } ) ,
32
+ ...( dynamicWidthProp && { width : Math . max ( minWidth , clientRectWidth ) } )
33
+ } ) ) ;
34
+ }
27
35
} ,
28
- [ container . current , setHeight , setWidth ]
36
+ [ setSizeState , minWidth , minHeight , dynamicHeightProp , dynamicWidthProp ]
29
37
) ;
30
38
31
- const observer = useRef ( new ResizeObserver ( recalculateSize ) ) ;
32
-
33
- // @ts -ignore
34
39
useEffect ( ( ) => {
35
40
if ( enableSizeMonitor && container . current ) {
41
+ // @ts -ignore
42
+ observer . current = new ResizeObserver ( recalculateSize ) ;
36
43
observer . current . observe ( container . current ) ;
37
-
38
- recalculateSize ( ) ;
39
- return ( ) => {
40
- observer . current . disconnect ( ) ;
41
- } ;
42
44
}
43
- } , [ ] ) ;
45
+ return ( ) => {
46
+ if ( observer . current ) {
47
+ observer . current . disconnect ( ) ;
48
+ }
49
+ } ;
50
+ } , [ recalculateSize ] ) ;
44
51
45
52
return {
46
- height : enableSizeMonitor ? height : heightProp ,
47
- width : enableSizeMonitor ? width : widthProp
53
+ height : dynamicHeightProp ? sizeState . height : heightProp ,
54
+ width : dynamicWidthProp ? sizeState . width : widthProp
48
55
} ;
49
56
} ;
0 commit comments