Skip to content

Instantly share code, notes, and snippets.

@manuel-mauky
Created June 15, 2020 18:18
Show Gist options
  • Save manuel-mauky/78fddc6c42f01e8345ef58bcc2a0b562 to your computer and use it in GitHub Desktop.
Save manuel-mauky/78fddc6c42f01e8345ef58bcc2a0b562 to your computer and use it in GitHub Desktop.
React-Hooks-Article: useMedia hook
import React, { useEffect, useState } from "react"
const useMedia = (query: string): boolean => {
const [matches, setMatches] = useState(false)
useEffect(() => {
const queryObject = window.matchMedia(query)
setMatches(queryObject.matches)
const listener = (e: MediaQueryListEvent) => {
setMatches(e.matches)
}
queryObject.addEventListener("change", listener)
return () => {
queryObject.removeEventListener("change", listener)
}
}, [query])
return matches
}
export const UseMediaExample = () => {
const matches = useMedia("(min-width: 600px)")
return (
<>
<p>Width is above 600 px: {matches ? "true" : "false"}</p>
</>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment