useOrientation
Tracks the device's current orientation.
Installation
Props
There is no props for this hook.
Key Features & Details
SSR & Initial Value
- The hook defaults to
'portrait'
ifwindow
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 onwindow.matchMedia('(orientation: portrait)')
for real-time updates.
Browser Compatibility
- Uses
addEventListener
/removeEventListener
if available, otherwise falls back toaddListener
/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 />
);