Allow to obtain match responses of given media query list items.
This hook relies on window.matchMedia to provide precise updates when some media query matches or not its requirements. It will also handle and dispose event listeners properly and avoid uncessary re-renders.
useMatchMedia(mediaQueries: string[]): boolean[]mediaQueries: a list of media queries to match for.
boolean[]: Each index matches its media query index inmediaQueriesparam.
export function UseMatchMedia(): JSX.Element {
const [mobile, tablet, desktop] = useMatchMedia([
"(max-width: 767px)",
"(min-width: 768px) and (max-width: 1023px)",
"(min-width: 1024px)",
]);
return (
<div>
<h1>useMatchMedia</h1>
<p>
useMatchMedia is a custom hook that returns a boolean value based on the
media query passed to it.
</p>
<p>It is useful for creating responsive components.</p>
<p>It is a wrapper around the window.matchMedia() method.</p>
<div>
<h2>Example</h2>
<ul>
<li>
Mobile: <span>{mobile ? "Yes" : "No"}</span>
</li>
<li>
Tablet: <span>{tablet ? "Yes" : "No"}</span>
</li>
<li>
Desktop: <span>{desktop ? "Yes" : "No"}</span>
</li>
</ul>
</div>
</div>
);
}At first render, it will update twice because it needs to wait for dom elements and window scope be ready, so at first render all elements returned by the hook will always be false. The immediate next state change, will provide the right values for the media queries.
MIT