Published on

useOrientation Hook React

useOrientation Hook React

useOrientation Hook React

useOrientation Code and Usage

useOrientation is a hook to detect changes in device orientation.

import { useState, useEffect } from "react";

const useOrientation = () => {
  const [orientation, setOrientation] = useState("");

  const handleOrientationChange = () => {
    const newOrientation = window.matchMedia("(orientation: portrait)").matches
      ? "portrait"
      : "landscape";
    setOrientation(newOrientation);
  };

  useEffect(() => {
    window.addEventListener("orientationchange", handleOrientationChange);
    handleOrientationChange();

    return () => {
      window.removeEventListener("orientationchange", handleOrientationChange);
    };
  }, []);

  return orientation;
};

// Usage
const OrientationExample = () => {
  const currentOrientation = useOrientation();

  return (
    <div>
      <p>Current Orientation: {currentOrientation}</p>
    </div>
  );
};