-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseWindowSize.ts
42 lines (34 loc) · 1.01 KB
/
useWindowSize.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import { useState, useEffect } from 'react';
import { throttle } from '../utils';
const events = new Set<() => void>();
const onResize = () => events.forEach(fn => fn());
export const useWindowSize = (options: { throttleMs?: number } = {}) => {
const { throttleMs = 100 } = options;
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight,
});
const handle = throttle(() => {
setSize({
width: window.innerWidth,
height: window.innerHeight,
});
}, throttleMs);
useEffect(() => {
if (events.size === 0) {
window.addEventListener('resize', onResize, true);
window.addEventListener('orientationchange', onResize, true);
}
// @ts-ignore
events.add(handle);
return () => {
// @ts-ignore
events.delete(handle);
if (events.size === 0) {
window.removeEventListener('resize', onResize, true);
window.removeEventListener('orientationchange', onResize, true);
}
};
}, []);
return size;
};