Hello everyone welcome to this new article where we are going to explore a new concept, the React Native Dimensions.

Dimensions in React Native is the default API by which we can calculate the width and the height of the screen or app window.

In a given app where it’s required to rotate the phone to use some functionality of the app, such as rotating the phone to enter the full screen mode of a youtube video or starting a video game, It’s important to keep track of the screen dimensions, so that you can adapt the app content a properly.

React Native Dimensions Basic Usage

To get the dimensions data we first need to import the API.

import { Dimensions } from 'react-native';

Then we can access the app dimensions as follows.

const {height, width} = Dimensions.get('window')

The Dimension.get() gets the height & width in two different screen sizes.
The window dimensions and the screen dimensions.

Where the window dimensions are the size of the visible application view, and the screen dimensions are the device’s dimensions.

As an example the window size can be lower than that of the screen, of the content of the app doesn’t fill the entire screen.

Calculating The Width and height of the screen

You are probably asking if the initial window sizes change or not, and how we could get the new values if yes?

The React Native Dimensions API comes with an event listener for the window size update that we can use Dimensions.addEventListener().

Dimensions.addEventListener("change", ({screen, window})=> {
  console.log("Dimensions: ", screen, window)
})

This way we can listen to the changes of both the screen and window dimensions.

Here is a quick example code of the entire usage

import React, { useState, useEffect } from "react";
 import { View, StyleSheet, Text, Dimensions } from "react-native";
 const window = Dimensions.get("window");
 const screen = Dimensions.get("screen");
 const App = () => {
   const [dimensions, setDimensions] = useState({ window, screen });
 const onChange = ({ window, screen }) => {
     setDimensions({ window, screen });
   };
 useEffect(() => {
     Dimensions.addEventListener("change", onChange);
     return () => {
       Dimensions.removeEventListener("change", onChange);
     };
   });
 return (
            {Window Dimensions: height - ${dimensions.window.height}, width - ${dimensions.window.width}}
       {Screen Dimensions: height - ${dimensions.screen.height}, width - ${dimensions.screen.width}}     

   );
 }
 const styles = StyleSheet.create({
   container: {
     flex: 1,
     justifyContent: "center",
     alignItems: "center"
   }
 });
 export default App;