본문 바로가기
웹/React

[React] 클래스형 컴포넌트의 생명 주기(LifeCycle)

by 테크케찰 2021. 8. 24.

React에서 클래스형 컴포넌트의 생명주기에 대해 간단히 정리해보겠습니다.

아래는 App 컴포넌트를 클래스형 컴포넌트로 선언하고 클래스형 컴포넌트를 호출한 예제 코드입니다.

...

class App extends React.Component<Props, State> {
  // 생성자 함수
  // State의 초기값 설정
  constructor(props: Props) {
    super(props);

    ...
  }
  
  ...

  // 렌더링되는 부분 정의
  // props나 state가 바뀌어 화면이 갱신되는 경우 호출
  render() {
    ...
  }

  // 부모로부터 받은 Props와 State를 동기화할 때 사용
  // Props로 State에 값을 설정 or State 값이 Props에 의존하여 결정된느 경우 사용
  static getDerivedStateFromProps(nextProps: Props, prevState: State) {
    console.log("getDerivedStateFromProps");

    // state에 설정하고 싶은 값 반환
    return null;
  }

  // 컴포넌트가 처음으로 화면에 표시된 이후 호출
  componentDidMount() {
    console.log("componentDidMount");
  }

  // render 함수가 호출된 후 실제로 화면이 갱신되기 직전에 이 함수 호출
  getSnapshotBeforeUpdate(prevProps: Props, prevState: State) {
    console.log("getSnapShotBeforeUpdate");

    return {
      testData: true,
    };
  }

  // props, state가 변경되어 render 함수가 호출된 후 호출되는 함수
  componentDidUpdate(
    prevProps: Props,
    prevState: State,
    snapshot: IScriptSnapshot
  ) {
    console.log("componentDidUpdate");
  }

  // props, state를 비교해 화면이 리렌더링될지 여부를 결정
  // true면 리렌더, false면 리렌더 x
  shouldComponentUpdate(nextProps: Props, nextState: State) {
    console.log("shouldComponentUpdate");
    return true;
  }

  // 컴포넌트가 화면에서 완전히 사라진 후 호출
  componentWillUnmount() {
    console.log("componentWillUnmount");
  }

  // 컴포넌트를 렌더링하는 부분에서 발생하는 에러를 처리하기 위한 함수
  componentDidCatch(error: Error, info: React.ErrorInfo) {
 
  }
}
...

생명주기의 호출 순서는 다음과 같습니다.

 

1) 컴포넌트가 생성되는 경우

constructor -> getDerivedStateFromProps -> render -> componentDidMount

 

2) 컴포넌트의 props가 업데이트되는 경우

getDerivedFromProps -> shouldComponentUpdate -> render -> getSnapShotBeforeUpdate -> componentDidUpdate

 

3) 컴포넌트의 state가 업데이트되는 경우

shouldComponentUpdate -> render -> getSnapShotBeforeUpdate -> componentDidUpdate

 

4) 컴포넌트 렌더링 중 에러가 발생한 경우

componentDidCatch

 

5) 컴포넌트가 화면에서 사라질 떄

componentWillUnmount

 

 

참고

http://www.yes24.com/Product/Goods/102280451

 

스무디 한 잔 마시며 끝내는 리액트+TDD - YES24

리액트와 테스트 코드를 동시에최근 서비스를 개발하기 위해서는 동작하는 프로그램을 작성하는 것 이외에도, 해당 서비스를 안정적으로 운영하고, 발생할 수 있는 버그를 발견할 수 있도록 테

www.yes24.com