Skip to content

watchMedia

Calls listener each time a CSS media query starts or stops matching.

It is not called with the current value: read it with matchesMedia. Outside a browser (no matchMedia), it does nothing and returns a function that does nothing.

Available since v3.1.5

import { watchMedia } from '@helpers4/browser';
// or, from the all-in-one package (same code, one install):
import { watchMedia } from 'helpers4/browser';
watchMedia(query: string, listener: function, options: WatchMediaOptions): function
ParameterTypeDescription
querystringA media query, e.g. `‘(prefers-reduced-motion: reduce)‘`
listenerfunctionReceives whether the query matches after the change
optionsWatchMediaOptionsCancellation — see WatchMediaOptions

function — A function that stops watching

The listener runs each time the query starts or stops matching.

const stop = watchMedia('(prefers-color-scheme: dark)', (dark) => {
  document.documentElement.dataset.theme = dark ? 'dark' : 'light';
});

Call the returned function, e.g. when a component is removed.

const stop = watchMedia('(min-width: 600px)', relayout);
// later
stop();

Options for watchMedia.

interface WatchMediaOptions {
  signal?: AbortSignalLike;
}

View source on GitHub