forked from streamich/react-use
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useMedia.ts
29 lines (23 loc) · 660 Bytes
/
useMedia.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
import { useEffect, useState } from 'react';
import { isClient } from './util';
const useMedia = (query: string, defaultState: boolean = false) => {
const [state, setState] = useState(isClient ? () => window.matchMedia(query).matches : defaultState);
useEffect(() => {
let mounted = true;
const mql = window.matchMedia(query);
const onChange = () => {
if (!mounted) {
return;
}
setState(!!mql.matches);
};
mql.addListener(onChange);
setState(mql.matches);
return () => {
mounted = false;
mql.removeListener(onChange);
};
}, [query]);
return state;
};
export default useMedia;