@@ -6,48 +6,62 @@ import { useState, useEffect, useMemo } from "react"
6
6
7
7
var { documentElement } = window . document ;
8
8
9
- let something ;
10
-
11
9
function getVpWidth ( ) {
12
- return Math . max (
10
+ return ( typeof window != 'undefined' ) ? Math . max (
13
11
documentElement . clientWidth ,
14
12
window . innerWidth || 0
15
- ) ;
13
+ ) : 0 ;
16
14
}
17
15
18
16
19
17
function getVpHeight ( ) {
20
- return Math . max (
18
+ return ( typeof window != 'undefined' ) ? Math . max (
21
19
documentElement . clientHeight ,
22
20
window . innerHeight || 0
23
- ) ;
21
+ ) : 0 ;
24
22
}
25
23
26
24
// =============== //
27
25
// Shared State //
28
26
// =============== //
29
27
28
+ // using separate variables since Babel
29
+ // transpilation saves a bit of filesize
30
+
30
31
var listeners = new Set ( ) ;
31
- var vpW = getVpWidth ( ) ;
32
- var vpH = getVpHeight ( ) ;
32
+ var vpW = 0 ;
33
+ var vpH = 0 ;
34
+
35
+ let hasListenerBeenAttached = false ;
36
+
33
37
34
- function onResize ( vpWidth , vpHeight ) {
38
+ // should only be called by *one* component once;
39
+ // will iterate through all subscribers
40
+ // afterwards
41
+
42
+ function onResize ( ) {
43
+ let vpWidth = getVpWidth ( ) ;
44
+ let vpHeight = getVpHeight ( ) ;
35
45
listeners . forEach ( function ( listener ) {
36
46
listener ( { vpWidth, vpHeight } ) ;
37
47
} ) ;
38
48
}
39
49
40
- window . addEventListener ( 'resize' , function ( ) {
41
- vpW = getVpWidth ( ) ;
42
- vpH = getVpHeight ( ) ;
43
- onResize ( vpW , vpH ) ;
44
- } ) ;
50
+
45
51
46
52
// =============== //
47
53
// the Hook //
48
54
// =============== //
49
55
50
56
function useViewportSizes ( debounce ) {
57
+ useLayoutEffect ( ( ) => {
58
+ if ( window && ! hasListenerBeenAttached ) {
59
+ hasListenerBeenAttached = true ;
60
+ window . addEventListener ( 'resize' , onResize ) ;
61
+ onResize ( ) ;
62
+ }
63
+ } , [ ] ) ;
64
+
51
65
const [ { vpWidth, vpHeight } , setState ] = useState ( ( ) => ( {
52
66
vpWidth : vpW , vpHeight : vpH
53
67
} ) ) ;
@@ -75,7 +89,7 @@ function useViewportSizes(debounce) {
75
89
return ( ) => listeners . delete ( listener ) ;
76
90
} , [ ] ) ;
77
91
78
- return [ vpWidth , vpHeight ] ;
92
+ return [ vpWidth , vpHeight , onResize ] ;
79
93
}
80
94
81
95
export default useViewportSizes
0 commit comments