Skip to content

Instantly share code, notes, and snippets.

@marcovincit
Created July 14, 2021 23:00
Show Gist options
  • Save marcovincit/f2c861daf77acd5bb03146941152d75a to your computer and use it in GitHub Desktop.
Save marcovincit/f2c861daf77acd5bb03146941152d75a to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
export default function useDeviceOrientation() {
const [absolute, setAbsolute] = useState(0);
const [alpha, setAlpha] = useState(0);
const [beta, setBeta] = useState(0);
const [gamma, setGamma] = useState(0);
useEffect(() => {
function updateDeviceOrientation(e) {
setAbsolute(e !== undefined ? e.absolute : 0);
setAlpha(e !== undefined ? e.alpha : 0);
setBeta(e !== undefined ? e.beta : 0);
setGamma(e !== undefined ? e.gamma : 0);
}
window.addEventListener("deviceorientation", updateDeviceOrientation);
updateDeviceOrientation();
return () =>
window.removeEventListener("deviceorientation", updateDeviceOrientation);
}, []);
return { absolute, alpha, beta, gamma };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment