CSS alone should drive most responsive behavior, but there are times when business logic depends on the viewport. matchMedia lets you subscribe to those breakpoint changes without polling the window size.
Reach for matchMedia when you need to hydrate components differently on desktop and mobile, lazy-load heavy assets, or coordinate analytics events. Avoid it for pure layout tweaks—CSS handles that without extra scripts.
const mediaQuery = window.matchMedia('(min-width: 768px)');
const updateExperience = (event) => {
if (event.matches) {
document.body.classList.add('layout--wide');
} else {
document.body.classList.remove('layout--wide');
}
};
mediaQuery.addEventListener('change', updateExperience);
updateExperience(mediaQuery);
Always pair the JavaScript listener with a CSS fallback so your application does not flash unstyled content or break for users with scripts disabled.