import {
  useEffect,
  useState,
  useMemo,
} from 'react'

export const useMediaQuery = (query: string) => {
  const mediaQuery = useMemo(() => matchMedia(query), [query])
  const [queryMatches, setQueryMatches] = useState(mediaQuery.matches)

  useEffect(() => {
    const listener = (event: MediaQueryListEvent) => {
      setQueryMatches(event.matches)
    }
    mediaQuery.addEventListener('change', listener)

    return () => {
      mediaQuery.removeEventListener('change', listener)
    }
  }, [mediaQuery])

  return queryMatches
}
