# useMediaQuery > Tracks whether a CSS media query currently matches. - Category: DOM - Package: `hookli` (install with `npm i hookli`) - Docs: https://hookli.vercel.app/docs/use-media-query ## Signature ```ts useMediaQuery(query: string, options?: UseMediaQueryOptions): boolean ``` ## Parameters - `query`: `string` — A CSS media query string, e.g. "(min-width: 768px)" or "(prefers-color-scheme: dark)". - `options`: `UseMediaQueryOptions` (default: `{}`) — SSR default and hydration behaviour. Optional. ## Returns - `matches`: `boolean` — Whether the query currently matches. Re-renders on every matchMedia change event, and starts from defaultValue on the server. ## Types ### UseMediaQueryOptions Configures the server value and mount behaviour. - `defaultValue`: `boolean` (default: `false`) — Value returned on the server and before hydration. - `initializeWithValue`: `boolean` (default: `true`) — Read the real match synchronously on mount. Set false to always start from defaultValue and avoid a hydration mismatch. ## Usage ```tsx import { useMediaQuery } from "hookli"; export function Demo() { const isWide = useMediaQuery("(min-width: 768px)"); return

{isWide ? "Desktop layout" : "Mobile layout"}

; } ``` ## Source `src/hooks/use-media-query/use-media-query.ts` ```ts import { useState } from "react"; import { useIsomorphicLayoutEffect } from "../use-isomorphic-layout-effect/use-isomorphic-layout-effect"; interface UseMediaQueryOptions { defaultValue?: boolean; initializeWithValue?: boolean; } const IS_SERVER = typeof window === "undefined"; export function useMediaQuery( query: string, options: UseMediaQueryOptions = {}, ): boolean { const { defaultValue = false, initializeWithValue = true } = options; const getMatches = (mediaQuery: string): boolean => { if (IS_SERVER) return defaultValue; return window.matchMedia(mediaQuery).matches; }; const [matches, setMatches] = useState(() => { if (initializeWithValue) return getMatches(query); return defaultValue; }); useIsomorphicLayoutEffect(() => { if (IS_SERVER) return; const matchMedia = window.matchMedia(query); const handleChange = () => setMatches(matchMedia.matches); handleChange(); matchMedia.addEventListener("change", handleChange); return () => { matchMedia.removeEventListener("change", handleChange); }; }, [query]); return matches; } ```