Skip to main content

useMediaQuery

Subscribe to media queries with window.matchMedia

github
View source code
import { useMediaQuery } from '@uhg-abyss/web/hooks/useMediaQuery';

Disclaimer

The useMediaQuery hook uses JavaScript to determine if the media query matches. This can cause issues with server-side rendering, as the window.matchMedia API is not available on the server. With the default options, the hook initializes to false and then updates after mount. If you need a specific SSR fallback value on first render, provide an initial value and set getInitialValueInEffect to false. We recommend using CSS media queries (through either the styled tool or the css prop) or the MediaQuery component for responsive design. If you only need to adjust functional behavior based on media queries, the useMediaQuery hook can be a good option.

Usage

The useMediaQuery hook leverages the window.matchMedia API and will return false if API is not available unless initial value is provided in the second argument.

Resize browser window to trigger window.matchMedia event:

Server-side rendering

For server-side rendering, choose behavior based on your first-render requirement. With the default (where getInitialValueInEffect is true), the hook always returns false initially and updates after mounting when window.matchMedia is available. If you provide an initialValue and want it applied on the initial render (including SSR), set getInitialValueInEffect to false.

const matches = useMediaQuery('(max-width: 700px)', true, {
getInitialValueInEffect: false,
});

Properties

useMediaQuery(
query: string,
initialValue?: boolean,
options?: {
getInitialValueInEffect: boolean;
}
): boolean;
Table of Contents