React의 LifeCycle은 크게 3가지로 나눌 수 있다.
마운트, 업데이트, 언마운트
컴포넌트가 만들어질때마다 가장 먼저 생성되는 메서드
// Class (클래스형)
constructor(props) {
super(props);
this.state = { count : 0 };
}
// Hooks (함수형)
const [count, setCount] = useState(0);
componentDidMount() {
// 외부 라이브러리 연동
// 컴포넌트에서 필요한 데이터 요청 (axios, fetch 등)
// DOM의 속성을 읽거나 직접 변경하는 작업
props로 받아온 값을 state로 동기화하는 작업을 해야할 때 사용
// Class (클래스형)
shouldComponentUpdate(nextProps) {
// 이전 값과 현재 값이 같을 경우 리렌더링 하지 않음
return nextProps.value !== this.props.value
}
// Hooks (함수형)
(prevProps, nextProps) => {
return nextProps.value === prevProps.value
}
getSnapshotBeforeUpdate(prevProps, prevState) {
if (prevProps.list.length < this.props.list.length {
const list = this.listRef.current
return list.scrollHeight - list.scrollTop
}
return null
}
// Class (클래스형)
componentDidUpdate(prevProps, prevState) {
...
}
// Hooks (함수형)
const Example = () => {
useEffect(() => {
...
});
}
// Class (클래스형)
componentWillUnmount() {
// 이벤트, setTimeout, 외부 라이브러리 인스턴스 제거
}
// Hooks (함수형)
const Example = () => {
useEffect(() => {
return () => {
...
}
}, []);
}