React hook to track media query matches
1import { useState, useEffect } from 'react';
2
3function useMediaQuery(query: string): boolean {
4 const [matches, setMatches] = useState(false);
5
6 useEffect(() => {
7 const media = window.matchMedia(query);
8
9 if (media.matches !== matches) {
10 setMatches(media.matches);
11 }
12
13 const listener = (e: MediaQueryListEvent) => {
14 setMatches(e.matches);
15 };
16
17 media.addEventListener('change', listener);
18
19 return () => media.removeEventListener('change', listener);
20 }, [matches, query]);
21
22 return matches;
23}
24
25// Usage example
26function ResponsiveComponent() {
27 const isDesktop = useMediaQuery('(min-width: 1024px)');
28 const isMobile = useMediaQuery('(max-width: 768px)');
29
30 return (
31 <div>
32 {isDesktop && <p>Desktop View</p>}
33 {isMobile && <p>Mobile View</p>}
34 </div>
35 );
36}Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.