[React] LifeCycle

jiyoung·2022년 12월 27일
0

리액트의 LifeCycle이란 무엇인가요?

리액트에서 컴포넌트를 만들 때 정말 중요한 개념 중 하나로 컴포넌트의 생성, 업데이트, 제거 과정을 말합니다.

1단계 - 생성(Mounting)

생성 단계는 컴포넌트가 constructor에 의해 초기화되고 rendering 과정을 거쳐 DOM에 최초로 그려지는 단계입니다. 생성 단계의 흐름은 다음과 같습니다.

  1. 컴포넌트의 base state가 constructor에 의해서 초기화 된다.
  2. getDerivedStateFromProps 실행(props로 받아온 것을 state에 넣어주고 싶을 때 사용)
  3. 초기화가 완료되면 render 메소드가 실행이 된다.
  4. 실제로 DOM에 컴포넌트를 mount한다.
  5. mounting이 완료되면 componentDidMount 메소드가 실행된다.(해당 컴포넌트에서 필요한 데이터를 요청하기 위해 axios,fetch를 통하여 요청을 하거나, DOM의 속성을 읽거나 직접 변경하는 작업 진행)

✅요약: constructor -> getDerivedStateFromProps -> render -> componentDidMount

2단계 - 변경(Updating)

변경 단계는 컴포넌트에 전달된 props 혹은 state에 변화가 생길 경우에 일어납니다. 변화가 생기면 리액트는 해당 컴포넌트의 re-rendering을 진행합니다.
변경 단계의 흐름을 정리해보면

props가 새롭게 전달되거나, setState()를 통해 상태(state)가 업데이트되면
1. getDerivedStateFromProps
2. shouldComponentUpdate(컴포넌트가 리렌더링할지 말지를 결정하는 메서드 - Virtual DOM에 그릴지 말지 결정하는 메소드)
3. 기존 컴포넌트를 새롭게 render한다.
4. getSnapshotBeforUpdate (변경이 진행되기 직전의 상태를 가져와서 특정 값을 반환하면 그 다음 발생하게 되는 componentDidUpdate 함수에서 받아와서 사용 가능)
3. DOM에 변화된 부분을 Update한다.
4. componentDidUpdate 메소드가 실행된다.

✅요약 : 새로운 Props 또는 State 변경 -> getDerivedStateFromProps -> render -> getSnapshotBeforUpdate -> componetnDidUpdate 순으로 실행

3단계 - 제거(Unmounting)

컴포넌트가 화면에서 사라지는것을 의미합니다. 언마운트에 관련된 생명주기 메서드는 componentWillUnmount 하나입니다.제거 단계는 DOM에 나타나있던 컴포넌트가 제거된 경우 사라지기 전에 componentWillUnmount가 실행됩니다.

🗒️위에서 알아본 컴포넌트의 라이프 사이클을 정리하면 다음과 같이 나타낼 수 있으며 선언 순서에 상관없이 life cycle 순서로 호출이 된 것을 알 수 있습니다.

import React from "react";

class ComponentLifeCycle extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      destroyed: false,
    };

    console.log("constructor() 메소드 호출");
  }

  static getDerivedStateFromProps() {
    console.log("getDerivedStateFromProps() 메소드 호출");

    return {};
  }

  componentDidMount() {
    console.log("componentDidMount() 메소드 호출");

    this.setState({ updated: true });
  }

  shouldComponentUpdate() {
    console.log("shouldComponentUpdate() 메소드 호출");

    return true;
  }

  getSnapshotBeforeUpdate() {
    console.log("getSnapshotBeforeUpdate() 메소드 호출");

    return {};
  }

  componentDidUpdate() {
    console.log("componentDidUpdate() 메소드 호출");
  }

  componentWillUnmount() {
    console.log("componentWillUnmount() 메소드 호출");
  }

  render() {
    console.log("render() 메소드 호출");

    return null;
  }
}

export default ComponentLifeCycle;

✨마치며 (작성중)


참고자료

0개의 댓글