useMediaQuery and usePrefersReducedMotion
SSR-safe React hooks for CSS media queries, built on useSyncExternalStore so they hydrate without mismatches and follow live changes. useMediaQuery takes any query and a server default, usePrefersReducedMotion reads the motion preference, and useBreakpoint returns the current Tailwind breakpoint. Falls back to the old listener API on older Safari. The preview shows the live breakpoint on a ruler and readouts for motion, colour scheme, contrast, hover, pointer and orientation.
Source
import * as React from "react";
export interface MediaQueryOptions {
/** Value used during server rendering and before hydration. Defaults to false. */
defaultValue?: boolean;
}
function subscribeTo(query: string) {
return (notify: () => void) => {
if (typeof window === "undefined" || !window.matchMedia) return () => {};
const list = window.matchMedia(query);
// Safari before 14 only has the deprecated addListener API.
if (list.addEventListener) {
list.addEventListener("change", notify);
return () => list.removeEventListener("change", notify);
}
list.addListener(notify);
return () => list.removeListener(notify);
};
}
/**
* Tracks a CSS media query. SSR-safe: the server and the first client render use
* `defaultValue`, then it follows the query, including live changes.
*/
export function useMediaQuery(query: string, { defaultValue = false }: MediaQueryOptions = {}): boolean {
const subscribe = React.useMemo(() => subscribeTo(query), [query]);
return React.useSyncExternalStore(
subscribe,
() => (typeof window !== "undefined" && window.matchMedia ? window.matchMedia(query).matches : defaultValue),
() => defaultValue,
);
}
/** True when the user asked the system to reduce motion. */
export function usePrefersReducedMotion(): boolean {
return useMediaQuery("(prefers-reduced-motion: reduce)");
}
/** Tailwind's default breakpoints, in px. */
export const BREAKPOINTS = { sm: 640, md: 768, lg: 1024, xl: 1280, "2xl": 1536 } as const;
export type Breakpoint = "base" | keyof typeof BREAKPOINTS;
/** The largest Tailwind breakpoint the viewport currently matches ("base" below sm). */
export function useBreakpoint(): Breakpoint {
const sm = useMediaQuery(`(min-width: ${BREAKPOINTS.sm}px)`);
const md = useMediaQuery(`(min-width: ${BREAKPOINTS.md}px)`);
const lg = useMediaQuery(`(min-width: ${BREAKPOINTS.lg}px)`);
const xl = useMediaQuery(`(min-width: ${BREAKPOINTS.xl}px)`);
const xxl = useMediaQuery(`(min-width: ${BREAKPOINTS["2xl"]}px)`);
return xxl ? "2xl" : xl ? "xl" : lg ? "lg" : md ? "md" : sm ? "sm" : "base";
}
