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

useMediaQuery.ts

32 lines852 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 })
10​
11 // Watch for changes
12 React.useEffect(() => {
13 if (typeof window !== 'undefined') {
14 // Create a matcher
15 const matcher = window.matchMedia(query)
16​
17 // Create our handler
18 const onChange = ({ matches }: { matches: boolean }) =>
19 setIsMatch(matches)
20​
21 // Listen for changes
22 matcher.addListener(onChange)
23​
24 return () => {
25 // Stop listening for changes
26 matcher.removeListener(onChange)
27 }
28 }
29 }, [isMatch, query, setIsMatch])
30​
31 return isMatch