Lifecycle에 대해 이해해보자 !
render
, componentDidMount
, componentDidUpdate
, componentWillUnmount등의 함수는 class에서 제공하는 메서드이다. 컴포넌트를 만들때 class로 생성하면 위의 메서드를 이용할 수 있고, 컴포넌트의 lifecycle
에 따라 각자의 메서드가 호출된다.
class Clock extends React.Component {
constructor() { // 1. 호출된다.
super();
this.state = {
date: new Date() // 2. 현재 시간으로 초기화
};
}
componentDidMount() { // 5. 함수 호출
this.timerID = setInterval( // 6. timer 추가
() => this.tick(),
1000
);
}
componentWillUnmount() { // 8. DOM에서 Clock 컴포넌트 삭제 -> 함수 호출
clearInterval(this.timerID); // 9. timer stopped
}
tick() {
this.setState({
date: new Date() // 7. this.state.date 값 변화(매초)
});
}
render() { // 3. render() 메소드 호출
return ( // 4. DOM에 return 요소 추가
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />, // ReactDom.render()의 첫 인자
document.getElementById('root')
);
사용하던 리소스가 더 이상 필요가 없으면 없애주는 것이 필요하다. 컴포넌트가 mounting
과 timer
를 추가하고 더 이상 화면에 unmounting
되는 순간 삭제해주어야 한다.
관련 메서드는 위에서 나온 componentDidMount
, componentWillUnmount
이다.
출처