useMediaQuery
ts
useMediaQuery(query: string): Service<{ readonly matches: boolean }>The matchMedia engine, exposed. One instance per query string.
Usage
js
import { useMediaQuery } from '@studiometa/js-toolkit';
const wide = useMediaQuery('(min-width: 64rem)');
// `props()` answers with no subscription, because asking a MediaQueryList is a read.
if (wide.props().matches) {
// …
}
const unsubscribe = wide.subscribe(({ matches }) => {
console.log(matches);
});Parameters
query— any media query string.
props() needs no subscription
Asking a MediaQueryList whether it matches is a read, so this service can answer without starting anything. Emissions are crossings.
That makes it the one service where props() outside a subscription is not a compromise.
Where it is used
data-mount="media:<query>" is this service, which is why that strategy is reversible: a crossing out unmounts the instance and a crossing back mounts it again.
See Mount strategies.
See also
usePrefersReducedMotion()— the named caseuseBreakpoint()— the named breakpoint set