File tree 1 file changed +27
-0
lines changed
packages/registry/src/hooks/browser
1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change
1
+ import * as React from "react" ;
2
+
3
+ /**
4
+ * Returns a boolean indicating if the current browser window matches the given media query.
5
+ *
6
+ * @param query - The media query to match.
7
+ *
8
+ * @example
9
+ * ```tsx
10
+ * const App = () => {
11
+ * const isMobile = useMediaQuery("(max-width: 768px)");
12
+ * return <div>{isMobile ? "Mobile" : "Desktop"}</div>;
13
+ * };
14
+ */
15
+ export function useMediaQuery ( query : string ) : boolean {
16
+ const mediaQueryList = React . useMemo ( ( ) => window . matchMedia ( query ) , [ query ] ) ;
17
+
18
+ const [ matches , setMatches ] = React . useState ( mediaQueryList . matches ) ;
19
+
20
+ React . useEffect ( ( ) => {
21
+ const listener = ( ) => setMatches ( mediaQueryList . matches ) ;
22
+ mediaQueryList . addEventListener ( "change" , listener ) ;
23
+ return ( ) => mediaQueryList . removeEventListener ( "change" , listener ) ;
24
+ } , [ mediaQueryList ] ) ;
25
+
26
+ return matches ;
27
+ }
You can’t perform that action at this time.
0 commit comments