-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
useMedia.tsx
44 lines (37 loc) · 916 Bytes
/
useMedia.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 { useState, useEffect } from 'react';
import json2mq from 'json2mq';
export function useMedia(
query: string | { [key: string]: any },
defaultMatches = true
) {
const [matches, setMatches] = useState(defaultMatches);
useEffect(
() => {
if (typeof window === 'undefined') {
return;
}
const mediaQueryList = window.matchMedia(
typeof query === 'string' ? query : json2mq(query)
);
let active = true;
const listener = () => {
if (!active) {
return;
}
if (mediaQueryList.matches) {
setMatches(true);
} else {
setMatches(false);
}
};
mediaQueryList.addListener(listener);
setMatches(mediaQueryList.matches);
return () => {
active = false;
mediaQueryList.removeListener(listener);
};
},
[query]
);
return matches;
}