useMediaQuery
Subscribes to a CSS media query and returns whether it currently matches. It re-renders only when the match state flips, and is hydration-safe.
When to use it
- Switching layouts or rendering different components by viewport width.
- Respecting
prefers-color-schemeandprefers-reduced-motion. - Detecting capabilities such as
(hover: hover)or(orientation: landscape). - Building your own helpers (
useBreakpoint,useIsDark, ...) on top.
Demo
The preview is an iframe, so queries match against the preview's width, not
the window's. On a wide window it keeps a fixed width; narrow your browser
below ~700px (where the preview goes full width) to cross the breakpoints,
and change your OS preferences to update the second demo. Open the Console
tab to see the onChange callback.
Loading demo…
Signature
interface UseMediaQueryOptions {
defaultValue?: boolean;
onChange?: (matches: boolean) => void;
}
function useMediaQuery(query: string, options?: UseMediaQueryOptions): boolean;
| Parameter | Type | Description |
|---|---|---|
query | string | A CSS media query, for example "(min-width: 768px)". |
options.defaultValue | boolean | Value on the server, during hydration, and without matchMedia. Defaults to false. |
options.onChange | (matches: boolean) => void | Called when the match state changes. Not called on mount. Latest version is used. |
Returns: true when the query currently matches.
Usage notes
- Hydration-safe. Built on
useSyncExternalStore: the server and the first client render both usedefaultValue, then React re-renders with the real value if it differs. ChoosedefaultValueto match your most likely layout (for exampletruefor a mobile-first design checking(max-width: 767px)) to minimize flashes. Client-only apps still get the real value on the first render. - Dynamic queries. Changing
queryre-subscribes and re-reads the match. - Graceful fallback. Without
window.matchMedia(SSR, some test environments) the hook returnsdefaultValueand never throws. onChangenever re-subscribes. Pass an inline function freely.- Extend it. Wrap the hook for your design system, as the demo's
useBreakpointdoes (see the example below). - Works with React 18 and 19, including StrictMode.
- Need to react to an element's size instead of the viewport's? Use
useElementSize.
Example
const isDesktop = useMediaQuery("(min-width: 1024px)");
const prefersDark = useMediaQuery("(prefers-color-scheme: dark)");
const reducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)", {
defaultValue: true, // be conservative until we know
});
// Build your own helpers on top
const useBreakpoint = (px: number) => useMediaQuery(`(min-width: ${px}px)`);
Hook source
View useMediaQuery source
useMediaQuery sourceuse-media-query.ts
import { useCallback, useEffect, useRef, useSyncExternalStore } from "react";
import { useLatest } from "./use-latest";
/** Options for {@link useMediaQuery}. */
export interface UseMediaQueryOptions {
/**
* Value returned on the server, during hydration, and whenever
* `window.matchMedia` is unavailable.
* Defaults to `false`.
*/
defaultValue?: boolean;
/** Called with the new match state whenever it changes (not on mount). */
onChange?: (matches: boolean) => void;
}
const hasMatchMedia = (): boolean =>
typeof window !== "undefined" && typeof window.matchMedia === "function";
/**
* Subscribes to a CSS media query and returns whether it currently matches.
*
* - **Hydration-safe:** built on `useSyncExternalStore`, so the server and the
* first client render both use `defaultValue`, then React re-renders with the
* real value if it differs.
* - **Live:** re-renders only when the match state flips, not on every
* viewport change.
* - **Dynamic queries:** changing `query` re-subscribes and re-reads the match.
* - **Graceful fallback:** returns `defaultValue` when `matchMedia` is
* unavailable (SSR, some test environments).
*
* Any media feature works, not just widths: `prefers-color-scheme`,
* `prefers-reduced-motion`, `orientation`, `hover`, `print` and so on.
*
* @param query - A CSS media query, for example `"(min-width: 768px)"`.
* @param options - Optional `defaultValue` and `onChange` callback.
* @returns `true` when the query currently matches.
*
* @example
* ```tsx
* const isDesktop = useMediaQuery("(min-width: 1024px)");
* ```
*
* @example
* ```tsx
* // Reflect the user's OS setting, assuming "no match" until hydrated
* const prefersDark = useMediaQuery("(prefers-color-scheme: dark)", {
* onChange: (dark) => console.log(dark ? "dark" : "light"),
* });
* ```
*
* @example
* ```tsx
* // Compose your own helpers on top
* const useBreakpoint = (px: number) => useMediaQuery(`(min-width: ${px}px)`);
* const usePrefersReducedMotion = () =>
* useMediaQuery("(prefers-reduced-motion: reduce)");
* ```
*
* For a live, editable example, see the [useMediaQuery docs page](https://altalyst-solutions.github.io/hookify/hooks/use-media-query).
*
* @see [Using media queries from JavaScript](https://developer.mozilla.org/en-US/docs/Web/CSS/Guides/Media_queries/Using_media_queries_from_JavaScript)
*/
export const useMediaQuery = (
query: string,
options?: UseMediaQueryOptions
): boolean => {
const defaultValue = options?.defaultValue ?? false;
const onChangeRef = useLatest(options?.onChange);
const subscribe = useCallback(
(notify: () => void) => {
if (!hasMatchMedia()) return () => {};
const mql = window.matchMedia(query);
mql.addEventListener("change", notify);
return () => mql.removeEventListener("change", notify);
},
[query]
);
const getSnapshot = useCallback(
() => (hasMatchMedia() ? window.matchMedia(query).matches : defaultValue),
[query, defaultValue]
);
const getServerSnapshot = useCallback(() => defaultValue, [defaultValue]);
const matches = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot
);
const previousRef = useRef(matches);
useEffect(() => {
if (previousRef.current === matches) return;
previousRef.current = matches;
onChangeRef.current?.(matches);
}, [matches, onChangeRef]);
return matches;
};