Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3095 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
3094 stevensc 1
import { useLayoutEffect, useState } from 'react'
2
 
3
const IS_SERVER = typeof window === 'undefined'
4
 
5
export function useMediaQuery(
6
  query,
7
  { defaultValue = false, initializeWithValue = true }
8
) {
9
  const getMatches = (query) => {
10
    if (IS_SERVER) {
11
      return defaultValue
12
    }
13
    return window.matchMedia(query).matches
14
  }
15
 
16
  const [matches, setMatches] = useState(() => {
17
    if (initializeWithValue) {
18
      return getMatches(query)
19
    }
20
    return defaultValue
21
  })
22
 
23
  // Handles the change event of the media query.
24
  function handleChange() {
25
    setMatches(getMatches(query))
26
  }
27
 
28
  useLayoutEffect(() => {
29
    const matchMedia = window.matchMedia(query)
30
    handleChange()
31
 
32
    matchMedia.addEventListener('change', handleChange)
33
    return () => {
34
      matchMedia.removeEventListener('change', handleChange)
35
    }
36
  }, [query])
37
 
38
  return matches
39
}