Handling Orientation
Respond to device rotation
Handling Orientation
When the device rotates, the screen dimensions change. react-native-device-geometry provides a robust event system to handle this.
The Problem
React Native's built-in Dimensions API sometimes lags behind the actual native view rotation, or doesn't provide the exact "safe" geometry immediately. This library queries the native window hierarchy directly.
Listening for Changes
Use the addListener method to subscribe to updates.
import { useEffect, useState } from 'react';
import { DeviceGeometry, EVENTS } from 'react-native-device-geometry';
export const OrientationAwareComponent = () => {
const [orientation, setOrientation] = useState('unknown');
useEffect(() => {
const sub = DeviceGeometry.addListener(EVENTS.ORIENTATION_CHANGE, (event) => {
setOrientation(event.metrics.orientation);
console.log('New width:', event.metrics.width);
});
return () => sub.remove();
}, []);
return <Text>Current Orientation: {orientation}</Text>;
};Using the Hook
For a simpler approach, just use the hook. It handles the subscription for you.
import { useDeviceGeometry } from 'react-native-device-geometry';
const MyComponent = () => {
const geometry = useDeviceGeometry();
// geometry will automatically update when rotation happens
return <Text>{geometry?.mainDisplay.metrics.orientation}</Text>;
};