useOrientation

Track the browser window or device rotation and orientation changes.

Device API

Orientation

Rotate your device or resize your window to see the magic.

📱
Fixed Content
0°Angle
Current Modelandscape primary
LayoutLandscape

Usage

import { useOrientation } from 'usehooks-ts'
 
export default function App() {
  const { angle, type } = useOrientation()
 
  return (
    <div>
      <p>Orientation Angle: {angle}°</p>
      <p>Orientation Type: {type}</p>
    </div>
  )
}

API

const { angle, type } = useOrientation()

Return Values

NameTypeDescription
anglenumberCurrent orientation angle in degrees
typestringOrientation type (e.g., 'portrait-primary')

Hook

import { useEffect, useState } from 'react'
 
export interface Orientation {
  angle: number
  type: string
}
 
const isBrowser = typeof window !== 'undefined'
 
export function useOrientation(): Orientation {
  const [orientation, setOrientation] = useState<Orientation>({
    angle: isBrowser ? (window.screen.orientation?.angle || 0) : 0,
    type: isBrowser ? (window.screen.orientation?.type || 'landscape-primary') : 'landscape-primary',
  })
 
  useEffect(() => {
    const handleOrientationChange = () => {
      setOrientation({
        angle: window.screen.orientation?.angle || 0,
        type: window.screen.orientation?.type || 'landscape-primary',
      })
    }
 
    window.addEventListener('orientationchange', handleOrientationChange)
    
    // Modern API
    if (window.screen.orientation) {
      window.screen.orientation.addEventListener('change', handleOrientationChange)
    }
 
    return () => {
      window.removeEventListener('orientationchange', handleOrientationChange)
      if (window.screen.orientation) {
        window.screen.orientation.removeEventListener('change', handleOrientationChange)
      }
    }
  }, [])
 
  return orientation
}