-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse-viewport-size.tsx
44 lines (36 loc) · 1.15 KB
/
use-viewport-size.tsx
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
43
44
import { useEffect, useRef, useState } from 'react';
/**
* Use the viewport dimensions (window inner height and width).
*
* Returns a new value when the window is resized. Updates are slightly
* throttled by deferring to the next animation frame.
*/
const useViewportSize = (): { height: number; width: number } => {
const af = useRef<number | undefined>();
const [size, setSize] = useState({ height: window.innerHeight, width: window.innerWidth });
useEffect(() => {
const update = (): void => {
if (af.current != null) {
return;
}
af.current = requestAnimationFrame(() => {
af.current = undefined;
setSize((current) => {
return current.height !== window.innerHeight && current.width !== window.innerWidth
? { height: window.innerHeight, width: window.innerWidth }
: current;
});
});
};
update();
window.addEventListener('resize', update);
return () => {
window.removeEventListener('resize', update);
if (af.current != null) {
cancelAnimationFrame(af.current);
}
};
}, []);
return size;
};
export { useViewportSize };