Initialization
: 처음에 constructor가 불리면서 props가 셋팅되고 state의 초기값이 설정되는 구간입니다.
render
: 브라우저에 최초로 그려지는 부분입니다.
componentWillUnmount
: 컴포넌트가 사라지면 해당 컴포넌트는 이미 인스턴스가 아니기 때문에 사라진 후의 작업은 할 수 없습니다. 그래서 사라지기 직전을 의미하는 componentWillUnmount 에 대한 설정만 가능합니다.
Updation에서 props
와 states
가 변경될 때는 결정적으로 하나의 차이가 있습니다.
props
일 경우에만 componentWillReceiveProps
라는 훅이 앞에 하나 더 있습니다. 그 이후에는 완전히 같습니다.
shouldComponentUpdate
이름이 말해 주듯이 컴포넌트가 업데이트 되어야 하는지 안되어야 하는지에 대한 결정을 할 수 있는 구간입니다.
이 부분이 상당히 중요합니다. 이 부분의 true
또는 false
의 리턴을 가지고 그 이후에 실제로 render가 되지 않게 조절을 할 수도 있습니다. 불필요하게 render 될 경우 방지 할때 도움이 됩니다. 그래서 react 컴포넌트의 성능 최적화에 아주 중요한 역할을 하는 lifecycle hook입니다.
이전 버전의 lifecycle hook을 배우는 이유는 현재 최신으로 바뀐 lifecycle hook에 대한 이해에 훨씬 더 도움이 되기 때문입니다.
생성 : 객체화되는 구간
마운트 : 그리는 구간 (render)
class App extends React.Component {
state = {
age: 39
};
constructor(props) {
super(props);
console.log("constructor", props);
}
render() {
// 최초 render (=mount)
console.log("render");
return (
<div>
<h2>
Hello {this.props.name} - {this.state.age}
</h2>
</div>
);
}
componentWillMount() {
console.log("componentWillMount");
} // 우리는 여기에 정의만 해놓으면 react가 알아서 부를것입니다.
componentDidMount() {
// 최초 render가 된 다음에 보통 여기서 여러가지 처리를 해줍니다.
// 타이머, api 요청 등등..
console.log("componentDidMount");
setInterval(() => {
console.log("setInterval");
this.setState(state => ({...state, age: state.age + 1}));
}, 1000);
} // 우리는 여기에 정의만 해놓으면 react가 알아서 부를것입니다.
}
결과
중간의 Warning 은 componentWillMount
가 이전 버전 이라고 알려주고 있습니다.
componentDidMount() {
// 최초 render가 된 다음에 보통 여기서 여러가지 처리를 해줍니다.
// 타이머, api 요청 등등..
console.log("componentDidMount");
setInterval(() => {
console.log("setInterval");
this.setState(state => ({...state, age: state.age + 1}));
}, 1000);
} // 우리는 여기에 정의만 해놓으면 react가 알아서 부를것입니다.
결과
setState()로 인해 state 값이 바뀌면서 render도 같이 실행되고 있습니다.
componentWillReceiveProps(nextProps) {
//nextProps : 바뀔 Props
console.log("componentWillReceiveProps", nextProps);
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate", nextProps, nextState);
//return false; // 여기서 false를 return한다면 render가 일어나지 않고 그 이후 hook들도 동작 하지 않습니다.
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log("componentWillUpdate", nextProps, nextState);
}
componentDidUpdate(prevProps, prevState) {
// render가 된 후에 불려지므로 인자 이름을 prev로 했습니다.
console.log("componentDidUpdate", prevProps, prevState);
}
shouldComponentUpdate(nextProps, nextState)
에 한번에 갑니다.예시
componentWillUnmpunt() {
clearInterval(this.intervalId);
}