상세 컨텐츠

본문 제목

[React] 컴포넌트 생명주기 (Lifecyle) 함수

React

by theseung 2020. 12. 16. 23:39

본문

반응형

컴포넌트 생성

  1. constructor
  2. getDerviedStateFromProp
  3. render (이 함수 실행 후 웹 문서에 출력)
  4. componentDidMount

생성 완료 후 props가 변경되거나 setState가 호출되는 경우

  1. getDerviedStateFromProp
  2. shouldComponentUpdate
  3. render
  4. getSnapshotBeforeUpdate
  5. 실제 DOM에 반영
  6. componentDidUpdate

생성 완료 후 forceUpdate가 호출되는 경우

  1. getDerviedStateFromProp
  2. render
  3. getSnapshotBeforeUpdate
  4. 실제 DOM에 반영
  5. componentDidUpdate

컴포넌트가 사라질 때

  1. componentWillUnmount
  2. 실제 DOM 반영

함수별 특징

constructor 함수

  • 인자값 : props

  • 맨 처음 생성 시에 한 번만 호출되는 함수

  • 항상 super 함수를 가장 위에 호출해야 합니다.
    super 함수는 property와 컴포넌트를 초기화 하는 함수임.

    constructor(props){
      super(props);
      ...
    }

getDerviedStateFromProp 함수

  • 인자값 : props, state

  • 정적 함수임 (this.props나 this.state 사용불가 / 값을 필요로 하는 경우 인자값 활용)

  • return 값으로 state 값을 추가/변경 가능 (빈 값 반환 시 state 변화 없음)

  • 이 함수 전에 실행되는 constructor 함수에는 state를 초기화 하지 않는 Warning 발생

    static getDerivedStateFromProps(props, state){
      ...
      return {}
    }

render 함수

  • 인자값 : 없음

  • 해당 함수에서 반환하는 JSX를 화면에 그려주는 함수

    render() {
      return (
          <div>화면에 출력될 내용</div>
      );
    }

componentDidMount 함수

  • 인자값 : 없음

  • 컴포넌트가 화면에 출력된 이후 실행될 내용을 해당 함수 안으로 넣으면 됨

    componentDidMount() {
      ...
    }

shouldComponentUpdate 함수

  • 인자값 : nextProps, nextState

  • 화면에 새로 출력할지 결정하는 함수

  • 데이터 변화를 비교하여 성능에 영향을 많이 줌

  • false를 반환하는 경우 render 할 내용에 변경 사항이 없다고 판단한고 이 함수 이후 생명주기가 실행되지 않음

  • true를 반환하는 경우 정상 실행

    shouldComponentUpdate(nextProps, nextState) {
      return true;
    }

getSnapshotBeforeUpdate 함수

  • 인자값 : prevProps, prevState

  • 인자값에서 반환되는 prevProps와 prevState는 변경되기 전에 값을 보여줌

  • render 함수 후에 실제 DOM에서 출력하기 전 실행되는 함수

  • 반환값은 componentDidUpdate 함수에 전달됨

  • 해당 함수와 componentDidUpdate 함수를 함께 적지 않는 경우 Warning 발생

    getSnapshotBeforeUpdate(prevProps, prevState){
      return {};
    }

componentDidUpdate 함수

  • 인자값 : prevProps, prevState, snapshot

  • 인자값 중 snapshot은 getSnapshotBeforeUpdate에서 반환된 값 / 없으면 undefined

  • 컴포넌트가 변환된 이후 DOM을 조작할 필요가 있을 경우 사용

    componentDidUpdate(prevProps, prevState, snapshot ){
      ....
    }

componentWillUnmount 함수

  • 인자값 : 없음

  • 컴포넌트와 관련된 이벤트, setInterval 등 이벤트 제거

    componentWillUnmount(){
      ...
    }
반응형

댓글 영역