Open History to see the last commit
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
37}