30% offEnding soon
useOrientationLoading saved progress…

useOrientation

Screen orientation describes how the screen is currently rotated, using a type such as portrait-primary and an angle such as 0. Build useOrientation so a component can read that pair and update when the Screen Orientation API reports a change. The hook must also return a predictable fallback during server rendering or in browsers that do not expose the API.

Signature

type Orientation = {
  type: string;
  angle: number;
};

function useOrientation(
  defaultValue?: Orientation // { type: 'portrait-primary', angle: 0 }
): Orientation;

Examples

// screen.orientation.type === 'landscape-primary'
// screen.orientation.angle === 90
useOrientation();
// { type: 'landscape-primary', angle: 90 }
// The Screen Orientation API is unavailable.
useOrientation({ type: 'landscape-secondary', angle: 270 });
// { type: 'landscape-secondary', angle: 270 }

Notes

  • Read both properties. Return the current screen.orientation.type and screen.orientation.angle as one object.
  • Reconcile after mount. A supported browser is authoritative even when its values differ from the supplied fallback.
  • Read on every change. Subscribe to the orientation object's change event and freshly read both properties inside the handler.
  • Handle unsupported environments. If screen or screen.orientation is unavailable, return defaultValue without throwing.
  • Subscribe once and clean up. Remove the exact listener from the same orientation object on unmount; ordinary rerenders must not reacquire or resubscribe.
  • Keep the scope focused. Do not lock the screen, use deprecated window.orientation, listen for device-motion events, or add a media-query fallback.