use-media-query

Subscribe to media queries with window.matchMedia
Import

Usage

use-media-query hook allows to subscribe to media queries. It receives media query as an argument and returns true if given media query matches current state. Hook relies on 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:

Breakpoint does not match
import { Badge } from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';
function Demo() {
const matches = useMediaQuery('(min-width: 900px)');
return (
<Badge color={matches ? 'teal' : 'red'} variant="filled">
Breakpoint {matches ? 'matches' : 'does not match'}
</Badge>
);
}

Server Side Rendering

When rendering a component on the server that uses useMediaQuery, it is important to pass the second argument initialValue, without it the server may generate html that cannot be correctly hydrated on client.

For example, the server will generate the html for clients using a smaller device. After the hydration, the hook will render again and return the result of the media query:

import { Badge } from '@mantine/core';
import { useMediaQuery } from '@mantine/hooks';
function Demo() {
const matches = useMediaQuery('(min-width: 900px)', false);
return (
<Badge color={matches ? 'teal' : 'red'} variant="filled">
Breakpoint {matches ? 'matches' : 'does not match'}
</Badge>
);
}`

Definition

function useMediaQuery(query: string, initialValue?: boolean): boolean;