React Native How to get orientation of device

The current code below will get the orientation however if the device is in Landscape view and you open the app it shows portrait view. After manual rotating the device it code below works correctly How do I get the orientation of the device when app starts.
#React #React Native

const ViewControllerProvider = (props) => {
  const [orientation, setOrientation] = useState('PORTRAIT');

  useEffect(() => {
    Dimensions.addEventListener('change', ({window: {width, height}}) => {
      if (width < height) {
        setOrientation('PORTRAIT');
      } else {
        setOrientation('LANDSCAPE');
      }
    });
  }, []);

  return (
    <ViewControllerContext.Provider value={{orientation}}>
      {props.children}
    </ViewControllerContext.Provider>
  );
};

export {ViewControllerProvider, ViewControllerContext};

38 thoughts on “React Native How to get orientation of device”

Leave a Comment