Lets dive straight into code
To create custom hooks that listens to device orientation we will be using Dimensions API to Detect changes in screen.
import { useState, useEffect } from 'react';
import { Dimensions } from 'react-native';
const useOrientation = () => {
const [orientation, setOrientation] = useState(getOrientation());
// Function to determine the current orientation
function getOrientation() {
const { width, height } = Dimensions.get('window');
return width > height ? 'LANDSCAPE' : 'PORTRAIT';
}
useEffect(() => {
const onChange = () => {
setOrientation(getOrientation());
};
// Listen for changes in screen dimensions
const subscription = Dimensions.addEventListener('change', onChange);
// Cleanup the event listener when the component is unmounted
return () => {
subscription.remove();
};
}, []);
return orientation;
};
export default useOrientation;
Top comments (0)