Cross browser device orientation React hook.
function App() {
const orientation = useDeviceOrientation();
return <p>{orientation}</p>;
}
Cross browser device orientation React hook.
function App() {
const orientation = useDeviceOrientation();
return <p>{orientation}</p>;
}
import React from "react"; | |
enum Orientation { | |
portrait = "portrait", | |
landscape = "landscape", | |
} | |
function getOrientation(): Orientation { | |
const { matches } = matchMedia("(orientation: portrait)"); | |
return matches ? Orientation.portrait : Orientation.landscape; | |
} | |
export default function useDeviceOrientation(): Orientation { | |
const [orientation, setOrientation] = React.useState<Orientation>(() => { | |
return getOrientation(); | |
}); | |
const orientationRef = React.useRef<Orientation>(orientation); | |
React.useEffect(() => { | |
orientationRef.current = orientation; | |
}, [orientation]); | |
React.useEffect(() => { | |
let nextTick: number; | |
(function tick() { | |
nextTick = requestIdleCallback(tick); | |
const orientation = getOrientation(); | |
if (orientation !== orientationRef.current) { | |
setOrientation(orientation); | |
} | |
})(); | |
return () => cancelIdleCallback(nextTick); | |
}, []); | |
return orientation; | |
} |