본문 바로가기
  • 바쁜 일상 속 작은 기억
React Native

[React Native] useIsFocused 란 무엇인가

by hellomingure 2022. 12. 29.

공식 문서에서는 useIsFocused를 이렇게 소개하고 있다.

 

https://reactnavigation.org/docs/use-is-focused/

 

reactnavigation.org

 

화면의 포커스 상태에 따라 다른 콘텐츠를 랜더링 하고 싶을 때, useIsFocused Hook 을 사용한다. 이 훅을 사용하면, 초점이 변경될 때 화면에 대한 리랜더링을 시키는 트리거가 된다.

공식문서만 봐서는 사실 이게 무슨말인지 정확하게 이해하는데 시간이 좀 걸렸다. 공식문서를 바탕으로 이 내용을 간단하게 생각해보자.

 

우선, 이 useIsFocused 가 사용된 screen 에서 이 값은 항상 true 이다.

import { useIsFocused } from '@react-navigation/native';

function Profile() {
  const isFocused = useIsFocused();

  return <Text>{isFocused ? 'focused' : 'unfocused'}</Text>;
}

 

A Screen 에서 B Screen으로 이동할 때, 그리고 B screen에서 다시 A Screen으로 돌아오는 useIsFocused의 값 변화를 따져보자.

위 이미지에서 화면이 mount, unmount 되는 순서는 react native navigation lifecycle에 대해서 더 공부하면 좋을 것 같다. 

https://reactnavigation.org/docs/navigation-lifecycle/

 

https://reactnavigation.org/docs/navigation-lifecycle/

 

reactnavigation.org

 

아무튼, useIsFocused 공식문서에서 말하는 대로, 내가 킨 화면의 isFocused 값이 true 혹은 false 로 나타내 주니, 이 값을 trigger로 이용해서 useEffect를 이용하여 해당 스크린에 이벤트를 리랜더링 시키면 되는 것이다.