raddix

useMediaQuery

Subscribe and respond to changes to CSS media queries.

Installation

npm i @raddix/use-media-query

Usage

Basic example

In this example we will show a message if the screen size is less than 768px.

import { useMediaQuery } from '@raddix/use-media-query';
export const Example = () => {
const isMobile = useMediaQuery('(max-width: 768px)');
return <div>{isMobile ? 'Mobile' : 'Desktop'}</div>;
};

Using a number as a query

You can also pass a number as a query, in this case it will match the media query (min-width: ${number}px).

import { useMediaQuery } from '@raddix/use-media-query';
export const Example = () => {
const isLargeDevice = useMediaQuery(1024);
return <div>Large: {isLargeDevice ? 'Yes' : 'No'}</div>;
};

API

Parameters

NameDescriptionRequiredType
queryThe media query to match. It can be any valid media query, like `(max-width: 768px)` or a number.Yesstring | number

Return value

Returns true if the media query matches and false if it does not.