DEV Community

Cover image for Mobile Orientation (React-Native)
Vaibhav Shukla
Vaibhav Shukla

Posted on

Mobile Orientation (React-Native)

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.

Image description


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;

Enter fullscreen mode Exit fullscreen mode

Top comments (0)