Stateful hook that uses the matchMedia API.
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.
Install this package with npm
.
npm i @buildinams/use-match-media
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)");
...
};
If you want to provide a default value for the initial render (and in server), you can pass it as defaultValue
within the optional config object. This accepts boolean
, undefined
, or null
. For example:
import useMatchMedia from "@buildinams/use-match-media";
const MyComponent = () => {
const isSmall = useMatchMedia("(max-width: 768px)", { defaultValue: true });
...
};
Couple things to note:
- The default value will only be used on the initial render and SSR. By the second render, the hook will use the actual value matched.
- If theres already a match for the query, the hook will use the actual value matched instead of the default value.
- If left blank, the default value will be
false
.
You can conditionally listen to events by passing a isEnabled
prop in the config object. This accepts a boolean
value, and will only listen to events if the value is true
(default). For example:
import useMatchMedia from "@buildinams/use-match-media";
const MyComponent = () => {
const [isEnabled, setIsEnabled] = useState(false);
const isSmall = useMatchMedia("(max-width: 768px)", { isEnabled });
...
};
By default, the hook will use useEffect
to listen to events. However, you can use useLayoutEffect
instead by passing layoutEffect
in the config object. For example:
import useMatchMedia from "@buildinams/use-match-media";
const MyComponent = () => {
const isSmall = useMatchMedia("(max-width: 768px)", { layoutEffect: true });
...
};
This is SSR safe, and will only use useLayoutEffect
on the client.
This library requires a minimum React version of 17.0.0
.
Found an issue? Want a new feature? Get involved! Please contribute using our guideline here.