Open History to see the last commit
1import 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 && window.matchMedia(query).matches
8 }
9 })
10β
11 // Watch for changes
12 React.useEffect(() => {
13 if (typeof window !== 'undefined') {
14 if (!window.matchMedia) {
15 return
16 }
17β
18 // Create a matcher
19 const matcher = window.matchMedia(query)
20β
21 // Create our handler
22 const onChange = ({ matches }: { matches: boolean }) =>
23 setIsMatch(matches)
24β
25 // Listen for changes
26 matcher.addListener(onChange)
27β
28 return () => {
29 // Stop listening for changes
30 matcher.removeListener(onChange)
31 }
32 }
33 }, [isMatch, query, setIsMatch])
34β
35 return isMatch
36}