Back to library
⚛️Reacttypescriptintermediate

useMediaQuery Hook

React hook to track media query matches

hooksresponsivebrowser

Code

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}

Quick Tips

  • Click the "Copy" button to copy the code to your clipboard
  • This code is production-ready and can be used in your projects
  • Check out related snippets below for more examples

Build Your Own Snippet Library

Organize your team's code snippets with Snippetly. Share knowledge and boost productivity across your organization.