Skip to content

Instantly share code, notes, and snippets.

@okmr-d
Last active January 25, 2022 19:47
Show Gist options
  • Save okmr-d/3496882873f0d48cb57153a65eed26ec to your computer and use it in GitHub Desktop.
Save okmr-d/3496882873f0d48cb57153a65eed26ec to your computer and use it in GitHub Desktop.
useBreakpoints hooks (useMediaQuery を簡単に使えるようにしたやつ)
import { useMediaQuery } from "./useMediaQuery"
const breakpoints = {
sm: 640,
md: 768,
lg: 1024,
xl: 1280,
"2xl": 1536,
}
type BreakpointKey = keyof typeof breakpoints
/**
* example:
* const isSmall = useBreakpoint("sm") // >= 640px
*/
export const useBreakpoint = (key: BreakpointKey) =>
useMediaQuery(`(min-width: ${breakpoints[key]}px)`)
import { useState, useEffect } from "react"
/**
* example:
* const isLargeOrMore = useMediaQuery("(min-width: 1024px)")
*/
export const useMediaQuery = (query: string) => {
const [matches, setMatches] = useState(
typeof window === "undefined" ? false : window.matchMedia(query).matches
)
useEffect(() => {
const media = window.matchMedia(query)
if (media.matches !== matches) {
setMatches(media.matches)
}
const listener = () => setMatches(media.matches)
window.addEventListener("resize", listener)
return () => window.removeEventListener("resize", listener)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [query])
return matches
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment