React - Life Cycle

lsjoon·2024년 9월 1일
0

React

목록 보기
6/6

컴포넌트가 생성되고 업데이트되고, 파괴되는 일련의 과정

클래스형(Class) 컴포넌트


생성 (Mount)
constructor(props)
static getDerivedStateFromProps(nextProps, prevState)
render()
componentDidMount()

업데이트 (Update)
static getDerivedStateFromProps(nextProps, prevState)
shouldComponentUpdate(nextProps, nextState)
render()
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate(prevProps, prevState, snapshot)

제거
componentWillUnmount()

생성 (Mount)

  • constructor
    - 컴포넌트가 생성될 때 가장 먼저 호출
    - 초기 상태(state)를 설정하거나, 컴포넌트가 필요로 하는 다른 초기 설정 수행
  constructor(props) {
    super(props);
    console.log("constructor");
  }
  • static getDerivedStateFromProps
    - 컴포넌트가 생성되거나 업데이트 될 때 호출
    - props로부터 파생된 state 생성 (상태를 props에 맞게 동기화 할 때 사용)
  static getDerivedStateFromProps(nextProps, prevState) {
    console.log("getDerivedStateFromProps");
    if (nextProps.color !== prevState.color) {
      return { color: nextProps.color };
    }
    return null;
  }
  • render
    - 컴포넌트의 UI 정의, JSX를 반환하며 이 JSX가 DOM으로 변환
  • componentDidMount
    - 컴포넌트가 DOM에 삽입된 직후 호출
    - 네트워크 요청, DOM 조작, 타이머 설정 등 초기화 작업에 주로 사용

업데이트 (Update)

  • getDerivedStateFromProps
    - 위와 동일

  • shouldComponentUpdate
    - 컴포넌트가 업데이트 되어야 하는지 여부를 결정
    - default는 'true', 성능 최적화를 위해 필요한 경우에만 구현

  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);
    // 숫자의 마지막 자리가 4면 리렌더링하지 않습니다
    return nextState.number % 10 !== 4;
  }
  • render
    - 위와 동일
  • static getSnapshotBeforeUpdate
    - 컴포넌트가 변경된 내용을 DOM에 반영하기 직전에 호출 (= 컴포넌트가 변하기 전)
    - 스크롤 위치 등을 저장 (반환값은 componentDidUpdate에서 사용 가능행
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("getSnapshotBeforeUpdate");
    if (prevProps.color !== this.props.color) {
      return this.myRef.style.color;
    }
    return null;
  }
  • componentDidUpdate
    - 컴포넌트의 업데이트가 완료되고, DOM에 변화가 반영된 후 호출
    - 네트워크 요청, DOM 관련 작업 진행
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate", prevProps, prevState);
    if (snapshot) {
      console.log("업데이트 되기 직전 색상: ", snapshot);
    }
  }

제거 (Unmount)

  • componentWillUnmount
    - 컴포넌트가 화면에서 사라지기 직전에 호출
  componentWillUnmount() {
    console.log("componentWillUnmount");
  }

+ 라이프사이클 메서드

  • componentDidCatch
    - React 16에서 새롭게 도입
    - 컴포넌트 렌더링 도중 에러가 발생했을 때, 멈추는 것이 아닌 오류 UI를 보여줌
    • 자신의 에러는 잡아내지 못하며, this.props.children으로 전달되는 컴포넌트에서 발생하는 에러만 잡아낼 수 있음
componentDidCatch(error, info) {
    this.setState({
        error: true
    });
    console.log({ error, info });
}

함수형 (Function) 컴포넌트


생성, 업데이트, 제거

  • useEffect
    - componentDidMount, componentDidUpdate, componentWillUnmount의 역할 모두 수행
    - useEffect 안의 함수는 컴포넌트가 마운트되거나 업데이트될 때 호출
    - return문에서 반환되는 함수는 컴포넌트가 언마운트될 때 호출
    - 두 번째 매개변수로 전달된 배열([ ])은 의존성 배열로, 배열에 명시된 값변경될 때만 useEffect가 실행

import React, { useState, useEffect } from 'react';

function MyComponent() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    // componentDidMount와 componentDidUpdate에 해당
    console.log('Component did mount or update');

    // componentWillUnmount에 해당
    return () => {
      console.log('Component will unmount');
    };
  }, [count]); // count가 변경될 때마다 실행
}
profile
중요한 것은 꺾여도 그냥 하는 마음

0개의 댓글