-
Notifications
You must be signed in to change notification settings - Fork 4.7k
Expand file tree
/
Copy pathindex.js
More file actions
37 lines (34 loc) · 798 Bytes
/
index.js
File metadata and controls
37 lines (34 loc) · 798 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
/**
* WordPress dependencies
*/
import { useState, useEffect } from '@wordpress/element';
/**
* Runs a media query and returns its value when it changes.
*
* @param {string} [query] Media Query.
* @return {boolean} return value of the media query.
*/
export default function useMediaQuery( query ) {
const [ match, setMatch ] = useState(
() =>
!! (
query &&
typeof window !== 'undefined' &&
window.matchMedia( query ).matches
)
);
useEffect( () => {
if ( ! query ) {
return;
}
const updateMatch = () =>
setMatch( window.matchMedia( query ).matches );
updateMatch();
const list = window.matchMedia( query );
list.addListener( updateMatch );
return () => {
list.removeListener( updateMatch );
};
}, [ query ] );
return !! query && match;
}