forked from nodejs/nodejs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseMediaQuery.ts
More file actions
33 lines (24 loc) · 751 Bytes
/
useMediaQuery.ts
File metadata and controls
33 lines (24 loc) · 751 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
'use client';
import { useState, useEffect } from 'react';
const useMediaQuery = (query: string) => {
const [matches, setMatches] = useState(() => {
if (typeof window === 'undefined') {
return false;
}
return window.matchMedia?.(query)?.matches ?? false;
});
useEffect(() => {
const { addEventListener, removeEventListener } = window.matchMedia?.(
query
) ?? {
matches: false,
addEventListener: () => {},
removeEventListener: () => {},
};
const handler = (event: MediaQueryListEvent) => setMatches(event.matches);
addEventListener('change', handler);
return () => removeEventListener('change', handler);
}, [query]);
return matches;
};
export default useMediaQuery;