상세 컨텐츠

본문 제목

개발중인앱(6) - useFocusEffect

react-native

by RNDK 2024. 9. 4. 11:54

본문

화면이 포커스 되었을때 실행해야 되는 함수를

useEffect(() => {
if (isFocused) {
//do something
}
}, [isFocused]);

이런식으로 실행하는 사람들이 분명있을 것이다.

react native에는 useFocusEffect라는 훅이 있다. 공식문서에서도 이것을 사용하는것을 권장한다. 
https://reactnavigation.org/docs/use-focus-effect/

 

useFocusEffect | React Navigation

Sometimes we want to run side-effects when a screen is focused. A side effect may involve things like adding an event listener, fetching data, updating document title, etc. While this can be achieved using focus and blur events, it's not very ergonomic.

reactnavigation.org

useEffect를 사용한다면 클린업 작업이라든지 최적화 작업을위해 추가적인 코드를 작성해야한다. 하지만 useFocsEffect의 경우

클린업 함수를 자동적으로 처리를 해주는 장점이있다. 사용법 또한 그리 어렵지 않으니 react-native프로젝트를 진행하고있다면 useFocusEffect를 사용하는 것을 적극 권장한다.

관련글 더보기

댓글 영역