useMediaQuery in React

From the React Custom Hooks cheat sheet · Browser & Storage Hooks · verified Jul 2026

useMediaQuery

Subscribe to a CSS media query - responsive logic in JS

jsx
import { useSyncExternalStore } from 'react'

function useMediaQuery(query: string) {
  return useSyncExternalStore(
    (cb) => {
      const mql = window.matchMedia(query)
      mql.addEventListener('change', cb)
      return () => mql.removeEventListener('change', cb)
    },
    () => window.matchMedia(query).matches,
    () => false,           // SSR fallback
  )
}

// Usage
const isMobile = useMediaQuery('(max-width: 768px)')
const prefersDark = useMediaQuery('(prefers-color-scheme: dark)')
const reducedMotion = useMediaQuery('(prefers-reduced-motion: reduce)')
💡 useSyncExternalStore is the right primitive - no tearing, SSR-safe
⚡ Return false from getServerSnapshot so SSR renders the desktop view by default
📌 Honor `prefers-reduced-motion` and `prefers-color-scheme` - free accessibility wins
🎯 Wrap breakpoint strings in a `breakpoints` map so they stay in sync with Tailwind
responsivecssa11y

Continue with React Custom Hooks

Save the full cheat sheet or work through every related task.

More React tasks

Back to the full React Custom Hooks cheat sheet