Back to articles
useMediaQuery: Complete Guide to Responsive Design in React

useMediaQuery: Complete Guide to Responsive Design in React

via Dev.to Reactreactuse.com

CSS media queries handle most responsive styling, but sometimes your React components need to know about the viewport, user preferences, or device capabilities at the JavaScript level. Maybe you need to conditionally render a mobile navigation, detect dark mode, or respect reduced motion preferences. The useMediaQuery hook from ReactUse gives you a reactive boolean that stays in sync with any CSS media query string. What is useMediaQuery? useMediaQuery wraps the browser's window.matchMedia API in a React hook. Pass it a media query string and it returns a boolean. It subscribes to the change event internally, so the value updates automatically when conditions change. import { useMediaQuery } from " @reactuses/core " ; function Example () { const isMobile = useMediaQuery ( " (max-width: 768px) " ); return < p > { isMobile ? " Mobile view " : " Desktop view " } </ p >; } The API is minimal: useMediaQuery ( query : string , defaultState ?: boolean ) => boolean Basic Usage: Mobile Detectio

Continue reading on Dev.to React

Opens in a new tab

Read Full Article
7 views

Related Articles