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:
optionsis required by the type; pass{}for the defaults. - Expect
defaultMatchesbefore hydration: on the server and during hydration the hook returnsdefaultMatches(falseby default), or thessrMatchMediaresult when it is set, then the real result. SetdefaultMatchesto the more likely value, ornoSsrwhen the result is used only on the client. - Write the query without
@media: a leading@mediais 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
| Parameter | Type | Description |
|---|---|---|
query required | string | No description |
options required | UseMediaQueryOptions | No description |
Returns
boolean