-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathuseMediaQuery.ts
43 lines (35 loc) · 1.38 KB
/
useMediaQuery.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
43
// Code from: https://usehooks-ts.com/react-hook/use-media-query
import { useEffect, useState } from "react";
const getMatches = (query: string): boolean => {
// Prevents SSR issues
if (typeof window !== "undefined") {
return window.matchMedia(query).matches;
}
return false;
};
/** Can be used to retrieve window dimensions with this React Hook which also works onResize. (Source: https://usehooks-ts.com/react-hook/use-media-query) */
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState<boolean>(getMatches(query));
useEffect(() => {
function handleChange() {
setMatches(getMatches(query));
}
const matchMedia = window.matchMedia(query);
// Triggered at the first client-side load and if query changes
handleChange();
// Use deprecated `addListener` and `removeListener` to support Safari < 14 (#135)
if (matchMedia.addListener) {
matchMedia.addListener(handleChange);
} else {
matchMedia.addEventListener("change", handleChange);
}
return () => {
if (matchMedia.removeListener) {
matchMedia.removeListener(handleChange);
} else {
matchMedia.removeEventListener("change", handleChange);
}
};
}, [query]);
return matches;
}