Skip to content

Instantly share code, notes, and snippets.

@enijar
Last active November 10, 2021 17:04
Show Gist options
  • Save enijar/6f590b56b45098af74c37e0ab0f2d6ff to your computer and use it in GitHub Desktop.
Save enijar/6f590b56b45098af74c37e0ab0f2d6ff to your computer and use it in GitHub Desktop.
Cross browser device orientation React hook.

Device Orientation Hook

Cross browser device orientation React hook.

Usage

function App() {
  const orientation = useDeviceOrientation();
  return <p>{orientation}</p>;
}

Online Demo

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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment