useMediaQuery
useMediaQuery is a custom React hook from the ShadCN library that simplifies the use of media queries within your React components. It enables responsive and adaptive user interfaces by allowing components to react to changes in the viewport or other media features dynamically.
Introduction
The useMediaQuery hook is a straightforward solution for incorporating media queries directly into your React components. By accepting a media query string and returning a boolean, it enables components to adjust their behavior or rendering automatically when the viewport changes. This hook removes the need for manual DOM listeners, providing an efficient way to handle responsiveness in modern web applications.
- Accepts a media query string as an argument.
- Returns a boolean value indicating whether the current viewport matches the provided media query.
- Automatically updates the returned value when the viewport changes, triggering a re-render of your component.
This allows your components to adapt their rendering or behavior based on the current state of the media query, without the need for complex event listeners or state management.
Basic useMediaQuery Example
You are viewing this on a small screen (<1024px wide).
(Resize your browser window to see the effect of the useMediaQuery hook.)