DEV Community

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

Posted on

3

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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs