BrowserBeginnerSSR-safehooks/browser/useMediaQuery.ts

useMediaQuery

matchMedia for breakpoints.

Import

TypeScript
import { useMediaQuery } from '@/hooks';

API

Signature

useMediaQuery(query, defaultValue?) → boolean

When to use

Responsive layout branching beyond CSS alone.

SSR / Next.js

Returns defaults on the server; hydrates on the client.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useMediaQuery
Editor
function MobileOnly() {
  const isMobile = useMediaQuery('(max-width: 768px)');
  return isMobile ? <nav>Mobile</nav> : <nav>Desktop</nav>;
}
Preview

Implementation source

Full library source for useMediaQuery — copy into your project when you are not installing a package yet.

hooks/browser/useMediaQuery.ts
import { useCallback, useState } from 'react';
import { isBrowser } from '../utility/isBrowser';
import { useIsomorphicLayoutEffect } from '../utility/useIsomorphicLayoutEffect';

/** SSR-safe CSS media query match. */
export function useMediaQuery(query: string, defaultValue = false): boolean {
  const getMatch = useCallback(() => {
    if (!isBrowser()) return defaultValue;
    return window.matchMedia(query).matches;
  }, [query, defaultValue]);

  const [matches, setMatches] = useState(getMatch);

  useIsomorphicLayoutEffect(() => {
    if (!isBrowser()) return;
    const mql = window.matchMedia(query);
    const onChange = () => setMatches(mql.matches);
    onChange();
    mql.addEventListener('change', onChange);
    return () => mql.removeEventListener('change', onChange);
  }, [query]);

  return matches;
}

Copy-paste example

useMediaQuery.example.tsx
'use client';

import { useMediaQuery } from '@/hooks';

export function MobileOnly() {
  const isMobile = useMediaQuery('(max-width: 768px)');
  return isMobile ? <nav>Mobile</nav> : <nav>Desktop</nav>;
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Values are safe during SSR (defaults). Gate layout-dependent UI with useMounted when needed.
  • Source of truth: open hooks/browser/useMediaQuery.ts for implementation details