React Life Cycle

jaehan·2022년 5월 3일
1

React

목록 보기
1/33
post-thumbnail

💻 Life Cycle

리액트는 MVC 패턴 중 View에 해당하는 라이브러리다. 그러다 보니 각각의 컴포넌트는 컴포넌트의 수명주기, 라이프 사이클이 존재한다.
컴포넌트의 수명은 일반적으로 페이지에서 렌더링 되기 전 준비 과정에서 시작해 페이지에서 사라질 때 끝이 난다.


👆 위의 사진이 life cycle의 전부이다


💡 마운트

마운트 될때 발생하는 생명주기

  • constructor
  • getDerivedStateFromProps
  • render
  • componentDidMount

constructor

constructor(props) {
    super(props);
    console.log("constructor");
}

👆 constructor 는 컴포넌트의 생성자 메서드입니다. 컴포넌트가 만들어지면 가장 먼저 실행되는 메서드이다.

getDerivedStateFromProps

static getDerivedStateFromProps(nextProps, prevState) {
    console.log("getDerivedStateFromProps");
    if (nextProps.color !== prevState.color) {
      return { color: nextProps.color };
    }
    return null;
}

👆 getDerivedStateFromPropsprops 로 받아온 것을 state 에 넣어주고 싶을 때 사용한다.

render

컴포넌트를 렌더링하는 메서드

render(){
  console.log("render");
  ...
}

componentDidMount

컴포넌트의 첫번째 렌더링이 마치고 나면 호출되는 메서드.
이 메서드가 호출되는 시점에는 우리가 만든 컴포넌트가 화면에 나타난 상태이다.


💡 업데이트

업데이트 될때 발생하는 생명주기

  • getDerivedStateFromProps
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate
  • componentDidUpdate

getDerivedStateFromProps 와 render는 업데이트와 마운트 둘다 발생한다.

shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);
    return nextState.number % 10 !== 4;
} // 숫자의 마지막 자리가 4이면 렌더링 하지 않는다.

👆 shouldComponentUpdate 메서드는 컴포넌트가 리렌더링 할지 말지를 결정하는 메서드입니다.
📌 React.memo와 비슷하다

getSnapshotBeforeUpdate

  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("getSnapshotBeforeUpdate");
    if (prevProps.color !== this.props.color) {
      return this.myRef.style.color;
    }
    return null;
}

👆 getSnapshotBeforeUpdate 는 컴포넌트에 변화가 일어나기 직전의 DOM 상태를 가져와서 특정 값을 반환하면 그 다음 발생하게 되는 componentDidUpdate 함수에서 받아와서 사용을 할 수 있다.

componentDidUpdate

 componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate", prevProps, prevState);
    if (snapshot) {
      console.log("업데이트 되기 직전 색상: ", snapshot);
    }
}

👆 componentDidUpdate 는 리렌더링이 마치고, 화면에 우리가 원하는 변화가 모두 반영되고 난 뒤 호출되는 메서드이다. 3번째 파라미터로 getSnapshotBeforeUpdate 에서 반환한 값을 조회 할 수 있습니다.


언마운트

언마운트는 컴포넌트가 화면에서 사라지는 것이다.
생명주기 메서드는 componentWillUnmount 하나가 있다.

componentWillUnmount

 componentWillUnmount() {
    console.log("componentWillUnmount");
 }

👆 componentWillUnmount는 컴포넌트가 화면에서 사라지기 직전에 호출된다.

0개의 댓글