라이프사이클
마운트, 업데이트, 언마운트 카테고리로 나뉨.
마운트
: DOM이 생성되고 웹 브라우저상에 나타나는 것
<마운트할 때 호출하는 메서드>
컴포넌트 만들기 -> constructor -> getDerivedStateFromProps -> render -> componentDidMount
- constructor: 컴포넌트를 새로 만들 때마다 호출되는 클래스 생성자 메서드
- getDerivedStateFromProps: props에 있는 값을 state에 넣을 때 사용하는 메서드
- render: 우리가 준비한 UI를 렌더링하는 메서드
- componentDidMount: 컴포넌트가 웹 브라우저상에 나타난 후 호출하는 메서드
업데이트
다음 네가지 경우에 업데이트
1. props가 바뀔 때
2. state가 바뀔 때
3. 부모 컴포넌트가 리렌더링될 때
4. this.forceUpdate 로 강제로 렌더링을 트리거할 때
<업데이트할 때 호출하는 메서드>
getDerivedStateFromProps -> shouldComponentUpdate -> render -> getSnapshotBeforeUpdate -> ComponentDidUpdate
- shouldComponentUpdate: 컴포넌트가 리렌더링을 해야 할지 말아야 할지 결정하는 메서드
- render: 컴포넌트를 리렌더링
- getSnapshotBeforeUpdate: 컴포넌트 변화를 DOM에 반영하기 바로 직전에 호출하는 메서드
- componentDidUpdate: 컴포넌트의 업데이트 작업이 끝난 후 호출하는 메서드
언마운트
: 마운트의 반대 과정, 즉 컴포넌트를 DOM에서 제거하는 것
언마운트할 때는 componentWillUnmount(컴포넌트가 웹 브라우저 상에서 사라지기 전에 호출하는 메서드)를 호출함.
getDerivedStateFromProps 메서드
마운트, 업데이트 때 props로 받아온 값을 state에 동기화
static getDerivedStateFromProps(nextProps, prevState) {
if(nextProps.value !== prevState.value) {
return {value: nextProps.value};
}
return null;
}
componentDidMount 메서드
컴포넌트를 만들고, 첫 렌더링을 다 마친 후 실행. 다른 자바스크립트 라이브러리 또는 프레임워크의 함수를 호출하거나 이벤트 등록, 네트워크 요청 같은 비동기 작업 처리
componentDidMount() { ... }
shouldComponentUpdate 메서드
props 또는 state를 변경했을 때, 리렌더링을 시작할지 여부를 지정함. 반드시 true 또는 false 값을 반환. (이 메서드를 따로 생성하지 않으면 기본적으로 true 반환)
shouldComponentUpdate(nextProps, nextState) { .. }
getSnapshotBeforeUpdate 메서드
render에서 만들어진 결과물이 브라우저에 실제로 반영되기 직전에 호출. 반환 값은 componentDidUpdate에서 파라미터 snapshot 값으로 전달받을 수 있음.
스크롤바 위치 유지와 같은 업데이트하기 직전의 값을 참고할 일이 있을 때 활용 됨.
getSnapshotBeforeUpdate(prevProps, prevState) {
if(prevState.array !== this.state.array) {
const{ scrollTop, scrollHeight } = this.list;
return { scrollTop, scrollHeight };
}
}
componentDidUpdate 메서드
리렌더링을 완료한 후 실행. getSnapshotBeforeUpdate 에서 반환한 값이 있다면 여기서 snapshot 값으로 전달받을 수 있음.
componentDidUpdate(prevProps, prevState, snapshot) { ... }
componentWillUnmount 메서드
컴포넌트를 DOM에서 제거할 때 실행
componentWillUnmont() { ... }
componentDidCatch 메서드
컴포넌트 렌더링 도중에 에러가 발생했을 때 애플리케이션이 먹통이 되지 않고 오류 UI를 보여줄 수 있게 해줌.
componentDidCatch(error, info) {
this.setState({
error: true
});
console.log({ error, info});
}