MatchMedia

Example

screenWidth >= 600px
HYDRATEEEEE
Resize the Browser

Example Source Code

Code

import { useEffect, useState } from "react";

export function useMatchMedia(query: string) {
	const mql = window.matchMedia(query);
	const [value, setValue] = useState(mql.matches);

	useEffect(() => {
		const change = (event: MediaQueryListEvent) => {
			setValue(event.matches);
		};

		mql.addEventListener("change", change);

		return () => {
			mql.removeEventListener("change", change);
		};
	}, []);

	return value;
}

Usage

import { useMatchMedia } from "@hooks/ReactMatchMedia";

function MatchMedia() {
	const greaterThan600Px = useMatchMedia("(min-width: 600px)");

	return (
		<>
			<div>
				<div>screenWidth &gt;= 600px</div>
				<div>{`${greaterThan600Px}`}</div>
			</div>
		</>
	);
}