컴포넌트가 생성(Mounting) → 업데이트(Updating) → 제거(Unmounting) 되는 일련의 과정
| 용어 | 설명 |
|---|---|
| ~ will | 어떤 작업 수행 전 실행되는 메서드 관련 용어 |
| ~ did | 어떤 작업 수행 후 실행되는 메서드 관련 용어 |
| mount | 컴포넌트에서 DOM이 생성되고 웹 브라우저 상에 나타나는 메서드 관련 용어 |
| update | 컴포넌트 내에서 변화 발생 시 수행되는 것을 의미 |
| unmount | 컴포넌트 내에서 DOM을 제거하는 메서드 관련 용어 |

Render Phase : 컴포넌트를 렌더링 하고, 필요한 변화를 계산하는 단계
Commit Phase : 변경사항을 실제 DOM에 적용하는 단계
class Counter extends React.Component {
**constructor**(props) {
super(props);
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
// ...
}
static getDerivedStateFromProps(nextProps, prevState) {
console.log("getDerivedStateFromProps");
if (nextProps.color !== prevState.color) {
return { color: nextProps.color };
}
return null;
}
import React, { Component } from 'react';
class MyComponent extends Component {
render() {
return (
<div>
<h1>Hello, React!</h1>
<p>This is a React component.</p>
</div>
);
}
}
componentDidMount() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
this.setState({ data });
});
}이미 mount 되어 DOM에 존재하는 컴포넌트를 re-rendering 하여 업데이트 하는 단계
- state 변경 시
- 부모 요소로부터 전달 받은 props 변경 시
- 중앙 상태값 (Context value 또는 redux store) 변경 시
- 부모 컴포넌트의 리렌더링이 일어날 시
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate", nextProps, nextState);
return nextState.number % 10 !== 4; // 리렌더링x
}
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);
}
}
컴포넌트가 DOM에서 제거되는 단계
componentWillUnmount() {
clearInterval(this.timerID);
}
React 16.8 버전 이후 도입된 React Hook을 통해 클래스 컴포넌트에서만 할 수 있던 state, lifecycle method 기능을 사용할 수 있게 됨
| 분류 | 클래스형 컴포넌트 | 함수형 컴포넌트 |
|---|---|---|
| Mounting | constructor() | 함수형 컴포넌트 내부 |
| Mounting | render() | return() |
| Mounting | componentDidMount() | useEffect(()⇒{}, []) |
| Updating | componentDidUpdate() | useEffect(()⇒{}, [state1, state2]) |
| UnMounting | componentWillUnmount() | useEffect(()⇒{ return () ⇒ { }}, [state1, state2]) |
https://ko.legacy.reactjs.org/docs/state-and-lifecycle.html
https://react.vlpt.us/basic/25-lifecycle.html
https://leetrue-log.vercel.app/react-rendering-basic