Expose a boolean that tracks a CSS media query.
Section: Common UI Hooks
Respond to media queries
tsx
tsx
function useMediaQuery(query: string) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
setMatches(media.matches);
const onChange = () => setMatches(media.matches);
media.addEventListener('change', onChange);
return () => media.removeEventListener('change', onChange);
}, [query]);
return matches;
}Explanation
Useful for responsive behavior that components need to know about in JavaScript.
Learn the surrounding workflow
Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.
Related commands
Same sheet · prioritizing Common UI Hooks
Handle clicks outside an element
Close menus or popovers when a click happens outside a ref.
Custom hook with options object
Prefer options objects for extensible APIs.