use-match-media
Stateful hook that uses the matchMedia API.
Introduction
This hook optimizes the use of the match media API by only creating a new listener when a unique query is made, avoiding the creation of unnecessary listeners and increasing efficiency.
This library is also SSR safe, and a default value can be provided for the initial render.
Installation
Install this package with npm
.
npm i @buildinams/use-match-media
Usage
To use the library simply import the hook and pass any custom media query.
import useMatchMedia from "@buildinams/use-match-media";
const MyComponent = () => {
const isTouch = useMatchMedia("(pointer: coarse)");
...
};
You can even use multiple queries in a single call. Though we recommend using separate hooks for each query to maximize performance.
import useMatchMedia from "@buildinams/use-match-media";
const MyComponent = () => {
const isTouchAndPortrait = useMatchMedia("(pointer: coarse) and (orientation: portrait)");
...
};
Using 'defaultValue'
If you want to provide a default value for the initial render (and in server), you can pass a second argument to the hook.
import useMatchMedia from "@buildinams/use-match-media";
const MyComponent = () => {
const isMobile = useMatchMedia("(max-width: 768px)", true);
...
};
Couple things to note:
- The default value will only be used on the initial render. By the second render, the hook will use the actual value matched.
- If left
undefined
, the default value will be false
.
Requirements
This library requires a minimum React version of 17.0.0
.
Requests and Contributing
Found an issue? Want a new feature? Get involved! Please contribute using our guideline here.