Skip to content

Instantly share code, notes, and snippets.

@gusfune
Created August 18, 2020 13:08
Show Gist options
  • Save gusfune/1ae54acc09c98554f09559b9777dfcf2 to your computer and use it in GitHub Desktop.
Save gusfune/1ae54acc09c98554f09559b9777dfcf2 to your computer and use it in GitHub Desktop.
/**
* useOrientation custom hook
* Usage:
* const { orientation } = useOrientation();
*/
import { useState, useEffect } from "react"
const useOrientation = () => {
const [orientation, setOrientation] = useState<
"portrait" | "landscape" | undefined
>("portrait")
let width: number
let height: number
const initialSetup = () => {
if (typeof window !== `undefined`) {
width = window.innerWidth
height = window.innerHeight
setOrientation(width / height >= 1 ? "landscape" : "portrait")
}
}
const listener = () => {
if (typeof window === "undefined" || !window.document) {
width = 0
height = 0
} else {
width = window.innerWidth
height = window.innerHeight
}
setOrientation(width / height >= 1 ? "landscape" : "portrait")
}
useEffect(() => {
initialSetup()
window.addEventListener("resize", listener)
return () => {
window.removeEventListener("resize", listener)
}
}, [initialSetup])
return {
orientation,
}
}
export { useOrientation }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment