Skip to content

Commit

Permalink
feat: add useMediaType hook
Browse files Browse the repository at this point in the history
  • Loading branch information
lolottetheclash committed Oct 21, 2022
1 parent 585d92e commit dce7d71
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/hook/useMediaType.ts
@@ -0,0 +1,22 @@
import { useCallback, useEffect, useState } from 'react'

export const useMediaType = (query: string): boolean => {
const [matches, setMatches]: [boolean, (value: boolean) => void] = useState<boolean>(false)

const handleChange = useCallback((event: MediaQueryListEvent) => {
setMatches(event.matches)
}, [])

useEffect(() => {
const matchQueryList = window.matchMedia(query)
setMatches(matchQueryList.matches)

matchQueryList.addEventListener('change', handleChange)

return () => {
matchQueryList.removeEventListener('change', handleChange)
}
}, [handleChange, query, setMatches])

return matches
}

0 comments on commit dce7d71

Please sign in to comment.