Skip to content

Instantly share code, notes, and snippets.

@enBonnet
Last active November 5, 2019 02:43
Show Gist options
  • Save enBonnet/d62031d278747883f3c328d075e4c731 to your computer and use it in GitHub Desktop.
Save enBonnet/d62031d278747883f3c328d075e4c731 to your computer and use it in GitHub Desktop.
Hooks
import { useState, useEffect } from "react"
import useWindowDimensions from "./useWindowDimensions"
const useIsMobile = () => {
const { width } = useWindowDimensions()
const [isMobile, setMobile] = useState(
window.innerHeight >= 900 ? false : true
)
useEffect(() => {
width >= 900 ? setMobile(false) : setMobile(true)
}, [width])
return { isMobile }
}
export default useIsMobile
import { useState, useEffect } from "react"
const useIsMobile = () => {
const [isMobile, setIsMobile] = useState()
useEffect(() => {
const innerWidth = window.innerWidth
innerWidth <= 768 ? setIsMobile(true) : setIsMobile(false)
}, [])
return isMobile
}
export default useIsMobile
import { useState, useEffect } from "react"
function getWindowDimensions() {
const { innerWidth: width, innerHeight: height } = window
return {
width,
height,
}
}
export default function useWindowDimensions() {
const [windowDimensions, setWindowDimensions] = useState(
getWindowDimensions()
)
useEffect(() => {
function handleResize() {
setWindowDimensions(getWindowDimensions())
}
window.addEventListener("resize", handleResize)
return () => window.removeEventListener("resize", handleResize)
}, [])
return windowDimensions
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment