Hook that tracks whether a CSS media query currently matches
Some responsive behaviour belongs in JavaScript, not only in CSS. A dashboard might render a compact list instead of a wide table on small screens, or a carousel might stop auto-playing when the user prefers reduced motion. Implement a React hook, useMatchMedia, that tells a component whether a CSS media query matches right now and re-renders the component when that changes.
function useMatchMedia(query: string, fallback?: boolean): boolean
query: any media query string, for example '(min-width: 900px)' or '(prefers-reduced-motion: reduce)'.fallback: the value to return when the browser has no window.matchMedia. Defaults to false.window.matchMedia(query).matches. Do not return a placeholder first and correct it in an effect.change event of the MediaQueryList. When it fires, re-render with the new value.query argument changes, return the new query’s value, stop listening to the old query, and listen to the new one.window.matchMedia is not a function (for example during server rendering or in an old test environment), return fallback and do not throw.function OrdersPage() {
const isWide = useMatchMedia('(min-width: 900px)');
const calmMotion = useMatchMedia('(prefers-reduced-motion: reduce)');
return (
<section>
{isWide ? <OrdersTable /> : <OrdersList />}
<Carousel autoPlay={!calmMotion} />
</section>
);
}
// Window is 1200px wide: isWide is true, so the table renders.
// The user narrows the window to 700px: the change event fires,
// isWide becomes false, and the list renders instead.
// No window.matchMedia available:
useMatchMedia('(min-width: 900px)'); // false
useMatchMedia('(min-width: 900px)', true); // true
window.matchMedia with a fake that records listeners and fires change events. Each call returns a new list object, like a real browser. Both addEventListener('change', fn) and the older addListener(fn) work. The event has matches and media, and the list’s matches property always reflects the current state.ReactDOM.flushSync.Object.assign(window, { useMatchMedia }); below “Do not edit below this line”. The tests use it to call your hook.