Skip to content

useOrientation

Returns the orientation of the device.

Installation

npx rabbithook@latest add use-orientation

Usage

App.tsx
import useOrientation from "@/hooks/use-orientation";
function Component() {
const { angle, type } = useOrientation();
return (
<>
<p>Angle: { angle }</p>
<p>Type: { type }</p>
</>
);
}

Code

use-orientation.ts
import { useState } from "react";
import useEventListener from "../use-event-listener";
interface IOrientation {
angle: number;
type: string;
}
const defaultValue = { angle: 0, type: "landscape-primary" };
const getOrientation = () => {
const { orientation } = window.screen;
if (orientation) return { angle: orientation.angle, type: orientation.type };
if (window.orientation) return { angle: typeof window.orientation === "number" ? window.orientation : 0, type: "" };
return null;
}
function useOrientation(initialState: IOrientation = defaultValue): IOrientation {
const [orientation, setOrientation] = useState(getOrientation() || initialState);
function handleChange() {
setOrientation(getOrientation() || initialState);
}
useEventListener("orientationchange", handleChange);
return orientation;
}
export default useOrientation;