useDeviceOrientation
React hook to provide the current orientation of the screen.
Add the hook via the CLI:
sh
npx @novajslabs/cli add useDeviceOrientation
sh
npx @novajslabs/cli add useDeviceOrientation
sh
pnpm dlx @novajslabs/cli add useDeviceOrientation
Or copy and paste the code into your project:
ts
import { useSyncExternalStore } from "react";
const orientationSubscribe = (cb: () => void) => {
window.addEventListener("orientationchange", cb);
return () => window.removeEventListener("orientationchange", cb);
};
const getOrientation = () => {
const { type, angle } = window.screen.orientation;
return JSON.stringify({ type, angle });
};
export const useDeviceOrientation = () =>
JSON.parse(useSyncExternalStore(orientationSubscribe, getOrientation));
js
import { useSyncExternalStore } from "react";
const orientationSubscribe = (cb) => {
window.addEventListener("orientationchange", cb);
return () => window.removeEventListener("orientationchange", cb);
};
const getOrientation = () => {
const { type, angle } = window.screen.orientation;
return JSON.stringify({ type, angle });
};
export const useDeviceOrientation = () =>
JSON.parse(useSyncExternalStore(orientationSubscribe, getOrientation));
Requirements
React 18.0.0 or higher
Return values
type
Type: "portrait-primary" | "portrait-secondary" | "landscape-primary" | "landscape-secondary"
The orientation type of the screen.
angle
Type: number
The rotation angle in degrees.