useMediaQuery hook
Subscribe to a CSS media query from React, without a resize listener or a layout read.
- #react
- #hooks
- #responsive
Reads a CSS media query as reactive state through window.matchMedia, instead of a resize listener that fires on every pixel.
Overview
A media query list exposes a matches boolean and a change event. The event fires only when the answer changes, while a resize listener measures the viewport on every frame of a drag.
Implementation
Usage example
Server rendering
The hook starts as false on the server and corrects itself after hydration. When the first paint matters, write the rule in CSS and keep the hook for behavioral differences, such as swapping a drawer for a sidebar.
Related entries
- useEventListener hook. Event subscription with a stable handler identity.
- Resizable split pane. Collapses to a stacked layout on a narrow viewport.
Related entries
useEventListener hook
Attach a DOM event listener once and keep the handler current, so a changing callback never detaches the listener.
useLocalStorage hook
A state hook that mirrors its value into localStorage, with safe hydration and cross-tab synchronization.
useIntersectionObserver hook
Track element visibility for lazy loading, infinite scroll and scroll-spy navigation.