[ 라이프 사이클 이란? ]

[ 마운트(Mount) ]
DOM이 생성되고 웹 브라우저상에 나타나는 것
[ 업데이트(Update) ]
Props나 state가 바뀌었을 때 업데이트한는 것
[ 언마운트(Unmount) ]
컴포넌트가 화면에서 사라질(제거될) 때
예시
import React, { Component } from 'react';
class LifeCycle extends Component {
constructor(props) {
super(props);
this.state = {
name: '1',
age: 1
}
}
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate(props, state) {
console.log('componentDidUpdate');
console.log('props : ', props);
console.log('state : ', state);
console.log('this.state : ', this.state);
// age값이 변경되었을 때만 실행하기
if ( state.age != this.state.age ) {
console.log('age change');
}
}
componentWillUnmount() {
console.log('componentWillUnmount');
}
render() {
return (
<div>
라이프사이클 {this.state.name}
<button onClick={() => {this.setState({name: 'hi'})}}>버튼</button>
<button onClick={() => {this.setState({age: 2})}}>버튼</button>
</div>
)
}
}
export default LifeCycle;