[React-Native] Life Cycle 이란?
1. 리액트에서 라이프 사이클 이란?
리액트는 컴포넌트 기반의 View를 중심으로 한 라이브러리 언어이다.
각각의 컴포넌트에는 라이프 사이클 즉, 컴포넌트의 생명주기가 존재한다.
컴포넌트의 수명은 보통 페이지에서 렌더링 되기 전 준비 과정에서 시작해서 페이지에서 사라질 때 끝이 난다.
2. 라이프 사이클의 유형
라이플 사이클은 크게 3가지 유형으로 나눌 수 있는데 생성이 될 때, 업데이트할 때, 제거할 때이다.
리액트에서는 이러한 작업을 Mount, Update, Unmount라고 한다.
Mount는 DOM이 생성되고 웹 브라우저 상에서 나타나는 것을 뜻한다.
Unmount는 DOM에서 제거되는 것을 뜻한다.
Update는 다음과 같은 4가지 상황에서 발생한다.
- Props가 바뀔 때
- State가 바뀔 때
- 부모 컴포넌트가 리 렌더링 될 때
- this.forceUpdate로 강제로 렌더링을 할 때
3. 라이프 사이클 메서드
constructor
컴포넌트가 처음 만들어질 때 실행되는 constructor(생성자)이다.
이 메서드에서 초기 state를 정할 수 있다.
// Class
class Expample extends React.Component {
constructor(props) {
super(props);
this.state = {count: 0};
}
// Hooks
const Example = () => {
const [count, setCount] = useState(0);
}
getDerivedStateFromProps
이 메서드는 리액트 16.3 버전 이후에 생긴 메서드이다.
props로 받아온 것을 state에 넣어주고 싶을 때 사용합니다.
props로 받아온 값을 state에 동기화시키는 용도로 사용하며, 컴포넌트가 마운트 될 때와 업데이트될 때 호출이 된다.
// Class
class Example extends React.Component {
static getDerivedStateFromProps(nextProps, prevState) {
if (nextProps.value !== prevState.value) {
return { value: nextProps.value }
}
return null
}
}
shouldComponentUpdate
이 메서드는 props나 state를 변경할 때, 리 렌더링을 할지 말지를 결정하는 메서드이다.
이 메서드에서는 반드시 true or false를 반환해주어야 한다.
이 메서드에서는 오직 성능 최적화 만을 위한 것이므로 렌더링 목적을 방지하는 목적으로 사용된다면 버그가 발생할 수 있다.
클래스형도 보통은 PureConmponent를 추천한다고 하고 Hooks에서도 props는 React.memo, state는 useMemo를 활용하면 렌더링 성능을 개선할 수 있다.
// Class
class Example extends React.Component {
shouldComponentUpdate(nextProps) {
return nextProps.value !== this.props.value
}
}
// Hooks
const Example = React.memo(() => {
...
},
(prevProps, nextProps) => {
return nextProps.value === prevProps.value
}
)
render
render는 가장 기초적인 메서드로써 가장 중요한 메서드이기도 하다.
컴포넌트를 렌더링 할 때 필요한 메서드로 필수 메서드이다.
컴포넌트에서는 render를 안 쓰고도 컴포넌트를 렌더링 할 수 있다.
// Class
class App extends React.Component {
render() {
return (
<View>
<Example />
</View>
)
}
}
// Hooks
const Example = () => {
return <View>컴포넌트 사항</View>
}
getSnapshotBeforeUpdate
이 메서드는 render에서 만들어진 결과가 브라우저에서 실제 반영되기 직전에 호출된다.
getSnapshotBeforeUpdate는 컴포넌트에 변화가 일어나기 직전의 DOM 상태를 가져와서 특정 값을 반환하면 그다음 발생하게 되는 componentDidUpdate 함수에서 받아와서 사용을 할 수 있습니다.
class Example extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevProps.list.length < this.props.list.length) {
const list = this.listRef.current
return list.scrollHeight - list.scrollTop
}
return null
}
}
componentDidMount
이 메서드는 컴포넌트를 만들고 첫 렌더링을 마친 후에 코드가 실행된다.
필요로 하는 데이터를 요청하기 위해 axios, fetch 등을 통하여 ajax 요청을 하거나, DOM의 속성을 읽거나 직접 변경하는 작업을 진행합니다.
Hooks에서는 useEffect로 구현이 가능하며, [] 의존성 배열을 비워야 똑같은 메서드로 구현이 가능하다.
// Class
class Example extends React.Component {
componentDidMount() {
...
}
}
// Hooks
const Example = () => {
useEffect(() => {
...
}, []);
}
componentDidUpdate
리 렌더링을 완료한 후 실행이 된다. 업데이트가 끝난 직후로, DOM관련 처리를 해도 무방하다.
// Class
class Example extends React.Component {
componentDidUpdate(prevProps, prevState) {
...
}
}
// Hooks
const Example = () => {
useEffect(() => {
...
});
}
componentWillUnmount
이 메서드는 컴포넌트 DOM에서 제거할 때 실행된다.
여기서 주로 DOM에 직접 등록했었던 이벤트를 제거하고,
만약에 'setTimeout'을 걸은 것이 있다면 'clearTimeout'을 통하여 제거를 합니다.
추가로 외부 라이브러리를 사용한 게 있고 해당 라이브러리에 dispose 기능이 있다면 여기서 호출해주시면 됩니다.
// Class
class Example extends React.Component {
coomponentWillUnmount() {
...
}
}
// Hooks
const Example = () => {
useEffect(() => {
return () => {
...
}
}, []);
}
componentDidCatch
이 메서드는 컴포넌트 렌더링 도중에 에러가 발생하면 애플리케이션이 멈추지 않고 오류 UI를 보여줄 수 있게 해 준다.
// Class
class Example extends React.Component {
componentDidCatch(error, info) {
console.log('에러가 발생했습니다.')
}
}
4. 상황에 따른 메서드 흐름
컴포넌트 생성부터 완료의 호출 순서
- constructor -> componentWillMount (depricated) -> render -> componentDidMount
prop변화가 있을 경우 호출 순서
- componentWillReceiveProps (depricated) -> shouldComponentUpdate (false 시 업데이트 취소) -> componentWillUpdate (depricated) -> render -> componentDidUpdate
state 변화 시 호출 순서
- shouldComponentUpdate (false 시 업데이트 취소) -> componentWillUpdate (depricated) -> render -> componentDidUpdate
컴포넌트를 제거할 때
- componentWillUnmount
구성요소에 문제가 있을 경우
- componentDidCatch
참고
[RN] React-Native 생명주기 는?
(RN의 한국어 자료가 많아지길 희망하며..)
medium.com
https://react.vlpt.us/basic/25-lifecycle.html
25. LifeCycle Method · GitBook
25. LifeCycle Method LifeCycle Method 는 한국어로 "생명주기 메서드" 라고 부릅니다. 생명주기 메서드는 컴포넌트가 브라우저상에 나타나고, 업데이트되고, 사라지게 될 때 호출되는 메서드들 입니다.
react.vlpt.us
https://koras02.tistory.com/92?category=967574#--%--getSnapshotBeforeUpdate%--