Skip to content

useMediaQuery

Reads whether a CSS media query matches and follows its changes.

useMediaQuery returns whether a media query currently matches and re-renders when the result changes. It is Base UI's useMediaQuery from @base-ui/react/unstable-use-media-query, re-exported through a Dify UI subpath.

tsx

Usage guidelines

  • Use it when the result must leave CSS: rendering a different component tree, passing a prop, or choosing behavior in JavaScript.
  • Prefer CSS for appearance: responsive variants such as sm: and container queries change layout without a render pass and without a mismatch during hydration.
  • Pass an options object: options is required by the type; pass {} for the defaults.
  • Expect defaultMatches before hydration: on the server and during hydration the hook returns defaultMatches (false by default), or the ssrMatchMedia result when it is set, then the real result. Set defaultMatches to the more likely value, or noSsr when the result is used only on the client.
  • Write the query without @media: a leading @media is stripped, so '(width < 40rem)' and '@media (width < 40rem)' behave the same.

Options

tsx

useMediaQuery.Options is a namespace alias of UseMediaQueryOptions.

Examples

Switch to a drawer below the small breakpoint

40rem is the Tailwind CSS sm breakpoint.

tsx

API reference

useMediaQuery

Parameters
ParameterTypeDescription
query requiredstringNo description
options requiredUseMediaQueryOptionsNo description

Returns

boolean