JavaScript Snippet

React useMediaQuery Hook

Difficulty: Medium

Mirroring CSS media queries inside React components keeps logic about responsive breakpoints, dark-mode preference, and reduced motion in one place. The useMediaQuery hook subscribes to a MediaQueryList so renders stay in sync with the browser. This snippet covers the basic match boolean, an SSR-safe variant with an initial fallback, and a useBreakpoint helper that maps named breakpoints onto Tailwind-style logic.

Code Snippets
/

React useMediaQuery Hook

React useMediaQuery Hook

Mirroring CSS media queries inside React components keeps logic about responsive breakpoints, dark-mode preference, and reduced motion in one place. The useMediaQuery hook subscribes to a MediaQueryList so renders stay in sync with the browser. This snippet covers the basic match boolean, an SSR-safe variant with an initial fallback, and a useBreakpoint helper that maps named breakpoints onto Tailwind-style logic.

JavaScript
Medium
3 snippets
react
hooks
code-template
css-media-queries

720 views

5

window.matchMedia(query) returns a MediaQueryList whose matches property reflects the current state and which fires a change event whenever the match flips. Reading the initial state synchronously inside the lazy initializer means the first render already has the right value (no flicker), and resyncing on subscribe handles the rare case where the value flipped between mount and effect-run. This is the right shape for prefers-color-scheme, prefers-reduced-motion, and any breakpoint.