I am trying to get the orientation of a device. I am able to do it with my current code and it works however there is one problem. When the device change orientation the component renders twice. I am not sure what I am doing wrong. How can I fix this code so that it does not render twice when the device orientation change
import React, {useEffect, useState} from 'react';
import {Dimensions} from 'react-native';
const OrientationContext = React.createContext();
const OrientationProvider = props => {
const [orientation, setOrientation] = useState({
orientation: 'LANDSCAPE',
screenWidth: null,
screenHeight: null,
});
const determineAndSetOrientation = () => {
let width = Dimensions.get('window').width;
let height = Dimensions.get('window').height;
if (width < height) {
setOrientation({
orientation: 'PORTRAIT',
screenWidth: width,
screenHeight: height,
});
} else {
setOrientation({
orientation: 'LANDSCAPE',
screenWidth: width,
screenHeight: height,
});
}
};
useEffect(() => {
determineAndSetOrientation();
const subscription = Dimensions.addEventListener('change', determineAndSetOrientation); // prettier-ignore
return () => {
subscription.remove();
};
}, []);
console.log(orientation, 'rendering');
return (
<OrientationContext.Provider value={{orientation}}>
{props.children}
</OrientationContext.Provider>
);
};
export {OrientationProvider, OrientationContext};