dotUI
dotUI
beta
  1. Hooks
  2. Sensors hooks
  3. useOrientation

useOrientation

Manage and respond to changes in device orientation with useOrientation.

"use client";

import React from "react";
import { useOrientation } from "@/lib/hooks/use-orientation";

function Demo() {
  const orientation = useOrientation();

  return (
    <section>
      <p className="text-xl font-bold">Orientation</p>
      <div className="mt-4 grid grid-cols-2 gap-4">
        <div>
          <p className="text-fg-muted">Angle</p>
          <p className="text-xl">{orientation.angle}</p>
        </div>
        <div>
          <p className="text-fg-muted">Type</p>
          <p className="text-xl">{orientation.type}</p>
        </div>
      </div>
    </section>
  );
}

Installation

Copy and paste the following code into your project.

import React from "react";

export function useOrientation() {
  const [orientation, setOrientation] = React.useState({
    angle: 0,
    type: "landscape-primary",
  });

  React.useLayoutEffect(() => {
    const handleChange = () => {
      const { angle, type } = window.screen.orientation;
      setOrientation({
        angle,
        type,
      });
    };

    const handleOrientationChange = () => {
      setOrientation({
        type: "UNKNOWN",
        angle: window.orientation,
      });
    };

    if (window.screen?.orientation) {
      handleChange();
      window.screen.orientation.addEventListener("change", handleChange);
    } else {
      handleOrientationChange();
      window.addEventListener("orientationchange", handleOrientationChange);
    }

    return () => {
      if (window.screen?.orientation) {
        window.screen.orientation.removeEventListener("change", handleChange);
      } else {
        window.removeEventListener("orientationchange", handleOrientationChange);
      }
    };
  }, []);

  return orientation;
}

Update the import paths to match your project setup.

Paramaters

The useOrientation hook does not accept any parameters.

Return values

NameTypeDescription
angle
number
The current orientation angle of the device in degrees.
type
string
The current orientation type of the device (e.g., ‘portrait-primary’, ‘landscape-primary’, ‘portrait-secondary’, ‘landscape-secondary’). If the type cannot be determined, it is ‘UNKNOWN’.

Built by mehdibha. The source code is available on GitHub.