h3/use's logo

h3/use

Command Palette

Search for a command to run...

useOrientation

Tracks the device's current orientation.

useOrientation
This component uses the useOrientation hook to get the current orientation of the device.

Current orientation: portrait

You are in portrait mode 📱

Try rotating your device or resizing the window.

Installation

Props

There is no props for this hook.

Key Features & Details

SSR & Initial Value

  • The hook defaults to 'portrait' if window is not available (e.g., during SSR).
  • On the client, the initial value reflects the current orientation.

State Updates

  • The hook updates its state immediately on mount and whenever the device orientation changes.
  • Uses the change event on window.matchMedia('(orientation: portrait)') for real-time updates.

Browser Compatibility

  • Uses addEventListener/removeEventListener if available, otherwise falls back to addListener/removeListener for older browsers.

Cleanup

  • The event listener is removed automatically when the component unmounts.

Return Value

  • The hook returns a string: either 'portrait' or 'landscape'.

Caveats & Best Practices

  • The hook is intended for use in the browser; on the server, it will always return 'portrait'.
  • Works for both mobile and desktop browsers that support the orientation media query.
  • If you need to support environments without window.matchMedia, consider a fallback.

Examples

Basic Usage

const orientation = useOrientation();
return <div>Orientation: {orientation}</div>;

Conditional Rendering

const orientation = useOrientation();
return orientation === 'portrait' ? (
  <PortraitComponent />
) : (
  <LandscapeComponent />
);