Skip to content

useMediaQuery ​

Category
Export Size
1.13 kB
Last Changed
2 years ago

Reactive Media Query. Once you've created a MediaQueryList object, you can check the result of the query or receive notifications when the result changes.

Demo ​

isLargeScreen: false
prefersDark: false

Usage ​

ts
import { 
useMediaQuery
} from '@vueuse/core'
const
isLargeScreen
=
useMediaQuery
('(min-width: 1024px)')
const
isPreferredDark
=
useMediaQuery
('(prefers-color-scheme: dark)')

Server Side Rendering and Nuxt ​

If you are using useMediaQuery with SSR enabled, then you need to specify which screen size you would like to render on the server and before hydration to avoid a hydration mismatch

ts
import { 
useMediaQuery
} from '@vueuse/core'
const
isLarge
=
useMediaQuery
('(min-width: 1024px)', {
ssrWidth
: 768 // Will enable SSR mode and render like if the screen was 768px wide
})
console
.
log
(
isLarge
.
value
) // always false because ssrWidth of 768px is smaller than 1024px
onMounted
(() => {
console
.
log
(
isLarge
.
value
) // false if screen is smaller than 1024px, true if larger than 1024px
})

Alternatively you can set this up globally for your app using provideSSRWidth

Type Declarations ​

ts
/**
 * Reactive Media Query.
 *
 * @see https://vueuse.org/useMediaQuery
 * @param query
 * @param options
 */
export declare function 
useMediaQuery
(
query
:
MaybeRefOrGetter
<string>,
options
?:
ConfigurableWindow
& {
ssrWidth
?: number
}, ):
ComputedRef
<boolean>

Source ​

Source • Demo • Docs

Contributors ​

Anthony Fu
Antério Vieira
Anthony Fu
Robin
IlyaL
Wahid Rizka Fathurrohman
SerKo
James Garbutt
Fernando Fernández
Adrien Foulon
Alex
Indrek Ardel
Zhousg
Young
Jelf
Dominik Freier
webfansplz
Eureka
karma
Alex Kozack
Jacob Clevenger

Changelog ​

7432f - feat(types): deprecate MaybeRef and MaybeRefOrGetter in favor of Vue's native (#4636)
c6c6e - feat: use useEventListener where it was not being used (#4479)
59f75 - feat(toValue): deprecate toValue from @vueuse/shared in favor of Vue's native
55965 - feat(useSSRWidth): add optional support for SSR in useMediaQuery and useBreakpoints (#4317)
3af75 - fix: the return value should be computed (#4403)
0a9ed - feat!: drop Vue 2 support, optimize bundles and clean up (#4349)

Released under the MIT License.