리액트에서 사용하는 component들은 라이프사이클 (생명주기)가 존재한다.
페이지가 렌더링되기 전인 준비과정에서 시작하여 페이지에서 사라질 때 끝난다.
❗️라이프사이클 메서드는 클래스형 컴포넌트에서만 사용이 가능하다. 함수형 컴포넌트에는 hook을 사용하여 비슷한 작업을 할 수 있다.
이 과정에서 라이프사이클은 크게 3단계로 나뉜다
1. Mount
2. Update
3. Unmount
마운트는 DOM이 생성되고 웹 브라우저상에 나타나는 것을 의미한다.
이 때 호출하는 메소드로는
📌 Did와 Will의 차이점
Will
은 어떤 작업을 작동하기 전에 실행되는 메서드이고,
Did
은 어떤 작업을 작동한 후에 실행되는 메서드이다.
render() {
return (
<div>
<h1>The number is: {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
)
}
컴포넌트는 props 또는 state가 변경되면 업데이트가 발생한다.
+parent 컴포넌트가 리렌더링될 때
+this.forceUpdate로 강제로 렌더링을 트리거 할때
마운트의 반대과정으로 다른 페이지로 이동해서 더 이상 컴포넌트가 필요하지 않을 때와 같은 경우에 컴포넌트를 DOM에서 제거하는 것이다.
componentWillUnmount()
: 컴포넌트가 웹 브라우저 상에서 사라지기 전에 호출하는 메서드📒 예제
impor React from 'react';
class App extends React.Component {
this.state = {
count: 0
};
add = () => {
this.setState(current => ({ count: current.count + 1 }));
};
minus = () => {
this.setState(current => ({ count: current.count - 1 }));
};
componentDidMount() {
console.log("Component rendered");
}
componentDidUpdate() {
console.log("I just updated");
}
componentWillUnmount() {
console.log("Good bye..")
}
render() {
console.log("I'm rendering");
return (
<div>
<h1>The number is: {this.state.count}</h1>
<button onClick={this.add}>Add</button>
<button onClick={this.minus}>Minus</button>
</div>
)
}
}
export default App;
💡콘솔
1. Mount
I'm rendering
component rendered
* render() 함수가 제일 먼저 호출되고, componentDidMount() 호출
2. Update
state 변경 시 - add or minus 버튼 클릭해서 state 값이 변경될 때 console
I'm rendering
I just updated
* setState()를 호출하면 컴포넌트를 호출하고, 먼저 render()를 호출한 다음 업데이트가 진행된 후 완료되면 componentDidUpdate 실행
3. Unmount
다른 페이지로 이동해서 더 이상 컴포넌트가 필요하지 않을 때
-> componentWillUnmount()가 호출된다.