matchMedia Subscribes To Breakpoint Changes

matchMedia evaluates a CSS breakpoint once and pushes updates through change events, keeping JS layout decisions on the same query string as the stylesheet.

TypescriptData Fetching

Code

typescriptsnippet
21 lines
// matchMedia turns a CSS breakpoint into subscribable state: the media string matches the stylesheet exactly,
// matches is a one-shot snapshot at query time, changes arrive via the change event
const query = window.matchMedia('(max-width: 768px)');

function render(layout: 'mobile' | 'desktop'): void {
  console.log('layout:', layout);
}

render(query.matches ? 'mobile' : 'desktop');

// MediaQueryListEvent carries matches: use the event value in the callback, never re-read the global
query.addEventListener('change', (event) => {
  render(event.matches ? 'mobile' : 'desktop');
});

// prefers-reduced-motion works the same way: respect the system's motion preference
const motionQuery = window.matchMedia('(prefers-reduced-motion: reduce)');
console.log('reduced motion:', motionQuery.matches);

// The old addListener API is deprecated; never poll window.innerWidth for breakpoints
document.body.dataset.layout = query.matches ? 'mobile' : 'desktop';

How the snippet works

Two window.matchMedia queries drive the file — the (max-width: 768px) breakpoint string and (prefers-reduced-motion: reduce) — with render as the single sink fed by both the one-shot snapshot and the change event callback.

What to watch for

  • window.matchMedia, document.body.dataset and MediaQueryListEvent are browser-only surfaces — evaluate this file in a page or the DevTools console, not a bare Node process.

Using it

The main signature reads function render(layout: 'mobile' | 'desktop')

The initial evaluation prints immediately — layout: from the one-shot query.matches check, reduced motion: from the motion query — while breakpoint flips arrive later through the change listener, each one triggering another layout: line.

Key statements

query.addEventListener('change', (event) => {
render(event.matches ? 'mobile' : 'desktop');
});

Interactive Tools for This Topic

FAQ

Does matchMedia Subscribes To Breakpoint Changes run in plain Node.js?
No — it touches `document` and `window`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.