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

useMediaQuery.ts

34 lines874 Bytes

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