[React-Native] Dimensions.get() 을 쓰면 안되는 이유

2023. 5. 17. 16:26·React-Native
반응형

Dimensions 이란?

RN에서 Dimensions은 보통 기기의 width(너비) 값, height(높이) 값을 구할 때 사용한다.

덧붙이자면, 다양한 (iOS, AOS) 기기의 자체의 width 와 height 값을 통해 의도한 UI를 구현하기 위해 사용한다.

 


Dimensions.get() 을 쓰면 안되는 이유

가로모드, 세로모드에 따른 변화된 width, height 값을 바로 불러오지 못한다.

처음 가져온 화면 크기에 고정된다.

 


대안

- useWindowDimensions() 사용

- Dimesions과 useState, useEffect를 활용
내가 생각하는 가장 좋은 대안은 react-native 에서 지원하는 useWindowDimensions() hook을 사용하는 것이다.

두번째 대안으로는 Dimesions를 useState와 useEffect로 값의 변화를 체크하는 것이다.

 


useWindowDimensions()

useWindowDimensions() 은 react-native 공식 문서에서도 나와있는 대안이다.

화면 변경, 즉 가로모드 세로모드 등의 변화가 있을때 값을 바로 업데이트 해준다.

 


useWindowDimensions() 사용

react-native 에서 지원하기 때문에 따로 라이브러리를 설치할 필요가 없다.
import {useWindowDimensions} from 'react-native';

const {width, height} = useWindowDimensions();

 


Dimensions과 useState, useEffect 활용

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

// state에 기기 widht, height 초기값 저장
const [deviceWidth, setDeviceWidth] = useState(windowWidth);
const [deviceHeight, setDeviceHeight] = useState(windowHeight);

// dimesions에 대한 변화가 일어날때 변화된 width, height 값 저장
useEffect(() => {
    const updateDimensions = () => {
      setDeviceWidth(Dimensions.get('window').width);
      setDeviceHeight(Dimensions.get('window').height);
    };
    const dimensionsHandler = Dimensions.addEventListener(
      'change',
      updateWidth,
    );

    return () => dimensionsHandler.remove();
  }, []);

 


참고 자료

https://reactnative.dev/docs/0.66/dimensions

 

Dimensions · React Native

useWindowDimensions is the preferred API for React components. Unlike Dimensions, it updates as the window's dimensions update. This works nicely with the React paradigm.

reactnative.dev

 

반응형
저작자표시 비영리 변경금지 (새창열림)
'React-Native' 카테고리의 다른 글
  • [React-Native] Android SDK 30 -> 31로 변경
  • [React-Native] ScrollView를 사용한 Native Picker 만들기
  • [React-Native] Node.js 빌드 에러 : address already in use :::8081
  • [React-Native] npm install 설치 시 npm ERR! code ERESOLVE
꾸매코더
꾸매코더
웹 / 앱 개발자
  • 꾸매코더
    꾸매코딩
    꾸매코더
  • 전체
    오늘
    어제
    • 분류 전체보기 (96)
      • JavaScript (18)
        • Deep Dive (0)
      • React (5)
      • React-Native (9)
      • CSS (3)
      • TypeScript (1)
      • CS (10)
      • GitHub (4)
      • Clone Coding (15)
        • Kakaotalk [HTML + CSS] (10)
        • Momentum [JavaScript] (5)
      • Project (30)
        • Timer Project (14)
        • Netflix [React + Hooks] (12)
        • ToDoList [React-Native] (4)
      • 회고 (1)
  • 링크

    • Github
  • hELLO· Designed By정상우.v4.10.3
꾸매코더
[React-Native] Dimensions.get() 을 쓰면 안되는 이유
상단으로

티스토리툴바