Skip to content

Commit bf2400c

Browse files
committed
add support for SSR with default values 0,0 and callback; addresses issue #1
note: this should be tested a bit before merging PR here
1 parent 7e3e453 commit bf2400c

File tree

1 file changed

+29
-15
lines changed

1 file changed

+29
-15
lines changed

src/index.js

Lines changed: 29 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,48 +6,62 @@ import { useState, useEffect, useMemo } from "react"
66

77
var { documentElement } = window.document;
88

9-
let something;
10-
119
function getVpWidth () {
12-
return Math.max(
10+
return (typeof window != 'undefined') ? Math.max(
1311
documentElement.clientWidth,
1412
window.innerWidth || 0
15-
);
13+
) : 0;
1614
}
1715

1816

1917
function getVpHeight () {
20-
return Math.max(
18+
return (typeof window != 'undefined') ? Math.max(
2119
documentElement.clientHeight,
2220
window.innerHeight || 0
23-
);
21+
) : 0;
2422
}
2523

2624
// =============== //
2725
// Shared State //
2826
// =============== //
2927

28+
// using separate variables since Babel
29+
// transpilation saves a bit of filesize
30+
3031
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+
3337

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();
3545
listeners.forEach(function(listener) {
3646
listener({ vpWidth, vpHeight });
3747
});
3848
}
3949

40-
window.addEventListener('resize',function(){
41-
vpW = getVpWidth();
42-
vpH = getVpHeight();
43-
onResize(vpW, vpH);
44-
});
50+
4551

4652
// =============== //
4753
// the Hook //
4854
// =============== //
4955

5056
function useViewportSizes(debounce) {
57+
useLayoutEffect(()=> {
58+
if(window && !hasListenerBeenAttached) {
59+
hasListenerBeenAttached = true;
60+
window.addEventListener('resize', onResize);
61+
onResize();
62+
}
63+
}, []);
64+
5165
const [{ vpWidth, vpHeight }, setState] = useState(() => ({
5266
vpWidth : vpW, vpHeight : vpH
5367
}));
@@ -75,7 +89,7 @@ function useViewportSizes(debounce) {
7589
return () => listeners.delete(listener);
7690
}, []);
7791

78-
return [vpWidth, vpHeight];
92+
return [vpWidth, vpHeight, onResize];
7993
}
8094

8195
export default useViewportSizes

0 commit comments

Comments
 (0)