컴포넌트가 생성되고 업데이트되고, 파괴되는 일련의 과정

생성 (Mount)
constructor(props)
static getDerivedStateFromProps(nextProps, prevState)
render()
componentDidMount()업데이트 (Update)
static getDerivedStateFromProps(nextProps, prevState)
shouldComponentUpdate(nextProps, nextState)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)제거
componentWillUnmount()
constructor(props) {
super(props);
console.log("constructor");
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log("getDerivedStateFromProps");
if (nextProps.color !== prevState.color) {
return { color: nextProps.color };
}
return null;
}
getDerivedStateFromProps
- 위와 동일
shouldComponentUpdate
- 컴포넌트가 업데이트 되어야 하는지 여부를 결정
- default는 'true', 성능 최적화를 위해 필요한 경우에만 구현
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate", nextProps, nextState);
// 숫자의 마지막 자리가 4면 리렌더링하지 않습니다
return nextState.number % 10 !== 4;
}
getSnapshotBeforeUpdate(prevProps, prevState) {
console.log("getSnapshotBeforeUpdate");
if (prevProps.color !== this.props.color) {
return this.myRef.style.color;
}
return null;
}
componentDidUpdate(prevProps, prevState, snapshot) {
console.log("componentDidUpdate", prevProps, prevState);
if (snapshot) {
console.log("업데이트 되기 직전 색상: ", snapshot);
}
}
componentWillUnmount() {
console.log("componentWillUnmount");
}
this.props.children으로 전달되는 컴포넌트에서 발생하는 에러만 잡아낼 수 있음componentDidCatch(error, info) {
this.setState({
error: true
});
console.log({ error, info });
}

import React, { useState, useEffect } from 'react';
function MyComponent() {
const [count, setCount] = useState(0);
useEffect(() => {
// componentDidMount와 componentDidUpdate에 해당
console.log('Component did mount or update');
// componentWillUnmount에 해당
return () => {
console.log('Component will unmount');
};
}, [count]); // count가 변경될 때마다 실행
}