일안하고블로그

[ React ] LifeCycle API 리액트 생명주기 정리 본문

React/State Menagement

[ React ] LifeCycle API 리액트 생명주기 정리

대한93 2018. 7. 30. 12:10


React 생명주기(LifeCycle)


리액트에서 정말 중요하지만 정리가 필요한 것이 리액트 생명주기입니다. 매번 할때 마다 구글링을 하고 정리가안되어 헤깔렸던 리액트 생명주기를 한번에 정리해 보겠습니다. 


컴포넌트 초기생성

컴포넌트 업데이트

컴포넌트 제거


컴포넌트 생성과정 



위의 예시에서 Result 버튼을 누르시고 console을 확인하시면 테스트 결과를 확인 할 수 있습니다. 


컴포넌트 생성과정


constructor -> componentWillMount -> render -> componentDidMount


컴포넌트의 실행과정을 살펴 보겠습니다.


constructor : 컴포넌트 생성자 함수


constructor(props) {
super(props);
console.log("제일먼저 constructor가 실행됩니다");
}


컴포넌트가 만들어 질 때 가장먼저 실행 됩니다.


componentWillMount


componentWillMount() {
console.log("componentWillMount 실행");
}


다음으로 실행되는 API는 componentWillMount입니다. 여기에서 알아 두어야 하는 단어는  Mount입니다.


Mount: 컴포넌트가 실행될때 "Mount된다" 라고 표현합니다.


componentWillMount는 최근 react16.3부터 UNSAFE_componentWillMount라는 이름으로 사용된다합니다. componentWillMount는 DOM에 접근하기 전이기 때문에 DOM 수정을 할 수 없습니다. componentWillMount 안에서는 props와 state를 수정하면 안됩니다.또한 componentDidMount와 constructor에서 componentWillMount기능을 대부분 처리 할 수 있어서 많이 사용되지 않습니다. 


componentDidMount : render을 거친 메서드


componentDidMount() {
console.log("render 이후 componentDidMount 실행");
}


componentDidMount는 컴포넌트가 만들어지고 render메서드를 거치고 만들어진 메서드입니다. 따라서 많은 것을 componentDidMount메서드에서 할 수 있습니다. 


comoponentDidMount

- 외부 라이브러리 연동

- 컴포넌트에 필요한 데이터 요청(fetch/axios/ajax/GraphQL)

- DOM 관련 작업 : 스크롤 작업 / 크기 읽어오기 / 등등


*componentDidMount 사용시 주의점 


이미 render을 거친 상태이기 때문에 state를 변경하면 render가 이미 실행된 상태이기 때문에 다시 render가 일어나서 깜박이거나 하는 상태가 발생합니다.


컴포넌트 업데이트


컴포넌트 업데이트는 props의 변화 혹은 state의 변화에 따라 결정 됩니다.


componentWillReceiveProps

componentWillReceiveProps(nextProps){
console.log("아직 props가 바뀌기 전");
}

아직 기존 props가 바뀌기 전에 실행됩니다. state가 props에 따라 변해야 하는 로직을 수행할때 사용됩니다. setState를 진행하여도 추가적으로 랜더링을 하지않습니다. React16.3부터 UNSAFE_componentWillReceiveProps로 사용된다고 합니다. 



static getDerivedStateFormProps 

static getDerivedStateFromProps(nextProps, prevState) {
console.log("여기서 setState를 하는것이아니거 특정 값에 nextProps값을 넣는것입니다.");
}

여기서는 값을 setState 하는 것이 아니고 특정 값에 state형태로 값을 리턴해줍니다. 말이 너무 어려워서 하단의 예제로 표시하겠습니다. 


shoudComponentUpdate 

shouldComponentUpdate(nextProps, nextState) {
//return false; 는 업데이트를 안하는경우
return true; // 업데이트를 하는경우
}

shoudComponentUpdate는 컴포넌트를 최적화 하는 작업에 좋은 API입니다. 쓸 때 없는 리랜더링 발생을 방지 하기 위해 사용됩니다. 


componentWillUpdate

componentWillUpdate(nextProps, nextState) {
// shoudComponentUpdate가 true로 반환되면 호출됨.
}

해당 API는 shoudComponentUpdate가 true를 반환 해야만 호출되는 API입니다. 주로 애니메이션 효과 초기화 , 이벤트 리스너 제거 작업을 합니다.  함수를 호출후 render()을 반환합니다. 


componentDidUpdate

componentDidUpdate(nextProps, nextState) {
console.log("this.props와 this.state가 변경되어있음.");
}


해당 API는 컴포넌트에서 render()을 호출한 후에 발생됩니다. 그리고 이전 값인 preProps와 preState를 조회 할 수 있습니다. 


컴포넌트 제거


componentWillUnmount

componentWillUnmount(){
// 이벤트, 외부 라이브러리 인스턴스 제거, setTimeout
}

컴포넌트가 필요하지 않게 되면 하나의 API가 호출됩니다. 해당 API에서는 이벤트를 제거하고 setTimeout을 걸은 것이 있다면 clearTimeout을 통해 제거 하고 외부 라이브러리를 사용한게 있고 해당 라이브러리에 dispose 기능이 있다면 여기서 호출해줍니다. 

import React, { Component } from 'react';

class Test extends Component {
state = {
number: 0,
}
constructor(props) {
super(props);
console.log("constructor");
}
componentWillMount() {
console.log("componentWillMount");
}
componentDidMount() {
console.log("componentWillMount");
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate");
console.log(nextState.number);
if (nextState.number === 2) {
// nextState.number 2이면 render /componentWillUpdate /componentDidUpdate 작동 x
return false;
}
return true;
}
componentWillUpdate(nextProps, nextState) {
console.log("componentWillUpdate");
}
componentDidUpdate(nextProps, nextState) {
console.log("componentDidUpdate");
}
plus = () => {
this.setState({
number: this.state.number + 1
});
}
render() {
console.log("render");
return (
<div>
<div>카운터 값 :</div>
<div>{this.state.number}</div>
<div><button onClick={this.plus}>플러스</button></div>
</div>
);
}
}


export default Test;

기본 자료 참조

https://junhobaik.github.io/js-react-lifecycle/


더 상세자료 참조

https://velopert.com/3631

'React > State Menagement' 카테고리의 다른 글

[ React ] Redux 시작하기 / 기초 -1  (0) 2018.07.17
Comments