How to prevent React Native component from rendering twice on orientation change

Viewed 287

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};
1 Answers

you can try this after changing your determineAndSetOrientation function like the following it might reduce some render.

const determineAndSetOrientation = () => {
  let width = Dimensions.get("window").width;
  let height = Dimensions.get("window").height;

  if (width < height && orientation.orientation !== "PORTRAIT") {
    setOrientation({
      orientation: "PORTRAIT",
      screenWidth: width,
      screenHeight: height,
    });
  } else if (orientation.orientation !== "LANDSCAPE") {
    setOrientation({
      orientation: "LANDSCAPE",
      screenWidth: width,
      screenHeight: height,
    });
  }
};
Related