[React Native] 인터넷 연결 상태 확인하기

han·2023년 8월 17일

ReactNative

목록 보기
1/8

인터넷 연결 상태 확인하기

모바일 앱을 개발하다보면 인터넷 연결 상태에 따라 동작이 변경되거나 UI가 변경되는 일이 있다.
이 글에서는 @react-native-community/netinfo 패키지를 사용해서 구현한다.

패키지 설치

yarn add @react-native-community/netinfo

iOS

cd ios && pod install

사용법

공식문서에도 나와있지만 사용법은 매우 간단하다.


// 구독
const unsubscribe = NetInfo.addEventListener(state => {
  ...
});

unsubscribe();


// 원타임
const state = await NetInfo.fetch();
...

이 글에서는 useNetInfo 훅을 할거다. 귀찮기 때문이다.
인터넷 연결 상태가 변경될 때 마다 갱신된 값을 받아볼 수 있다.

// A React Hook which updates when the connection state changes.
const state = useNetInfo();

결과

연결되지 않음

inactive

연결됨

profile
크로스 플랫폼과 사랑에 빠진 개발자의 글 연습

1개의 댓글

comment-user-thumbnail
2023년 8월 17일

좋은 글이네요. 공유해주셔서 감사합니다.

답글 달기