Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

useMediaQuery.ts

37 lines881 Bytes

1// @ts-nocheck
2​
3import React from 'react'
4​
5export default function useMediaQuery(query) {
6 // Keep track of the preference in state, start with the current match
7 const [isMatch, setIsMatch] = React.useState(() => {
8 if (typeof window !== 'undefined') {
9 return window.matchMedia && window.matchMedia(query).matches
10 }
11 })
12​
13 // Watch for changes
14 React.useEffect(() => {
15 if (typeof window !== 'undefined') {
16 if (!window.matchMedia) {
17 return
18 }
19​
20 // Create a matcher
21 const matcher = window.matchMedia(query)
22​
23 // Create our handler
24 const onChange = ({ matches }) => setIsMatch(matches)
25​
26 // Listen for changes
27 matcher.addListener(onChange)
28​
29 return () => {
30 // Stop listening for changes
31 matcher.removeListener(onChange)
32 }
33 }
34 }, [isMatch, query, setIsMatch])
35​
36 return isMatch