-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseWindowsDimensions.ts
More file actions
42 lines (35 loc) · 992 Bytes
/
useWindowsDimensions.ts
File metadata and controls
42 lines (35 loc) · 992 Bytes
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";
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height
};
}
export default function useWindowDimensions() {
const [isDesktop, setIsDesktop] = useState(false);
const { width, height } = getWindowDimensions();
if(width > 720 && !isDesktop) {
setIsDesktop(true);
}
const [windowDimensions, setWindowDimensions] = useState(
{ width, height }
);
useEffect(() => {
function handleResize() {
const { width, height } = getWindowDimensions();
if(width > 720 && !isDesktop) {
setIsDesktop(true);
} else if(isDesktop) {
setIsDesktop(false);
}
setWindowDimensions({ width, height });
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return {
...windowDimensions,
isDesktop
};
}