라이플 사이클
생명주기 메서드는 컴포넌트가 브라우저상에 나타나고, 업데이트되고, 사라지게 될 때 호출되는 메서드들 입니다. 추가적으로 컴포넌트에서 에러가 났을 때 호출되는 메서드도 있습니다.
어떤 컴포넌트가 마운트(생성되기 전에) 할 일이 있다면 componentWillMount()를 통해서 메서드 안에서 필요한 코드들을 컴포넌트가 생성되기 직전인 렌더함수가 호출되기 전에 해야할 일을 정의할 수 있습니다.
그러고 나서 render 함수가 호출이 되면, Mount가 되어 화면이 그려지고 그 다음에 화면이 그려질 일이 있다면 componentDidMount() 를 컴포넌트를 개발하는 개발자가 구현을 통해서 컴포넌트가 생성된 후 해야할 일을 할 수 있게 해줍니다.
라이프사이클에서는 총 3가지 마운트, 업데이트, 언마운트 카테고리로 나뉘게 됩니다.
1) 마운트: DOM이 생성되고 웹 브라우저상에 나타나는 것을 마운트라고 합니다
2) 업데이트: 업데이트 경우 총 4가지 경우에 업데이트를 합니다.
- props가 바뀔 때
- state가 바뀔 때
- 부모 컴포넌트가 리렌더링 될 때
- this.forceUpdate로 강제로 렌더링을 트리거할 때
3) 언마운트: 마운트의 반대 과정으로 컴포넌트를 DOM에서 제거하는 것을 언마운트라고 합니다.
componentWillMount(){
console.log('class => componentWillMount');
}
componentDidMount(){
console.log('class => componentWillMount');
}
render(){
console.log('class => render');
}
위와 같이 코드를 실행하게 되면 componentWillMount, render, componentDidMount 순으로 실행되는 것을 알 수 있습니다.
componentWillMount(){
console.log('class => componentWillMount');
}
componentDidMount(){
console.log('class => componentDidMount');
}
shouldComponentUpdate(nextProps, nextState){
console.log('class => shouldComponentUpdate');
}
componentWillUpdate(nextProps, nextState){
console.log('class => componentWillUpdate');
}
componentDidUpdate(nextProps, nextState){
console.log('class => componentDidUpdate');
}
render(){
console.log('class => render');
}
위와 같이 함수를 실행하게 되면 제일 먼저 DOM을 생성하고 웹 브라우저 상에 나타나는 것을 마운트과정이라고 합니다. 마운트 과정은 componentWillMount(), render(), componentDidMount() 가 나와서 rendering이 끝나게 됩니다.
끝난 상태에서 업데이트할 상황(props 또는 state가 바뀔 때)이 되면 그 상태가 위치하고 있는 컴포넌트의 render 메서드가 호출된다는 뜻인데, 그 때부터는
shouldComponentUpdate() 가 실행이 되고, componentWillUpdate() 가 호출이 될 것이고 , render가 호출될 것이고
componentDidUpdate()가 호출 될 것입니다.
클래스에서는 라이프사이클에 따라 정해진 메소드를 호출함으로써 원하는 코드를 실행할 수 있도록 도와줍니다.
'Language > React' 카테고리의 다른 글
[React] 배열 렌더링하기 (0) | 2020.12.28 |
---|---|
[React] 라이플 사이클 구현 하기 - skipping effect (0) | 2020.12.27 |
[React] 함수에서 state 사용법 - hook (0) | 2020.12.26 |
[React] props vs State (0) | 2020.12.25 |
[React] useRef, createRef 를 사용하는 방법 (0) | 2020.12.24 |
댓글