리액트의 생명주기(with class, function component)

sudyn·2023년 9월 21일

react

목록 보기
2/12

React 생명주기


컴포넌트가 생성(Mounting) → 업데이트(Updating) → 제거(Unmounting) 되는 일련의 과정

React 생명주기에서 다루는 용어들

용어설명
~ will어떤 작업 수행 전 실행되는 메서드 관련 용어
~ did어떤 작업 수행 후 실행되는 메서드 관련 용어
mount컴포넌트에서 DOM이 생성되고 웹 브라우저 상에 나타나는 메서드 관련 용어
update컴포넌트 내에서 변화 발생 시 수행되는 것을 의미
unmount컴포넌트 내에서 DOM을 제거하는 메서드 관련 용어

Class Component Lifecycle


Render Phase : 컴포넌트를 렌더링 하고, 필요한 변화를 계산하는 단계

Commit Phase : 변경사항을 실제 DOM에 적용하는 단계


1️⃣ Mounting

constructor()

  • 컴포넌트를 새로 생성하는 클래스 생성자 메서드
  • 생성된 함수를 바인딩하고, this.state에 객체를 할당해 초기값 설정
class Counter extends React.Component {
  **constructor**(props) {
    super(props);
    this.state = { counter: 0 };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    // ...
  }

getDerivedStateFromProps()

  • 부모 컴포넌트로부터 props를 전달받고 이때 return 하는 내용이 컴포넌트의 state가 됨
  • 마운트, 업데이트 시 render() 이전에 호출되는 메서드
  • 컴포넌트의 props, state 변경시마다 호출됨
static getDerivedStateFromProps(nextProps, prevState) {
    console.log("getDerivedStateFromProps");
    if (nextProps.color !== prevState.color) {
      return { color: nextProps.color };
    }
    return null;
  }

render()

  • 미리 구현한 HTML 을 화면상에 렌더링해주는 메서드
  • JSX나 React 요소 반환
import React, { Component } from 'react';

class MyComponent extends Component {
  render() {
    return (
      <div>
        <h1>Hello, React!</h1>
        <p>This is a React component.</p>
      </div>
    );
  }
}

componentDidMount()

  • 컴포넌트가 렌더링된 이후 호출되는 메서드
  • DOM 을 사용해야하는 외부 라이브러리 연동/ 네트워크요청(axios, fecch)
    componentDidMount() {
      fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => {
          this.setState({ data });
        });
    }

2️⃣ Updating

이미 mount 되어 DOM에 존재하는 컴포넌트를 re-rendering 하여 업데이트 하는 단계

리렌더링을 유발하는 조건

- state 변경 시
- 부모 요소로부터 전달 받은 props 변경 시
- 중앙 상태값 (Context value 또는 redux store) 변경 시
- 부모 컴포넌트의 리렌더링이 일어날 시

getDerivedStateFromProps()

  • Mount 과정에서도 동일하게 호출되었던 메서드
  • 부모 컴포넌트로부터 props를 전달받을 때, state에 값을 일치시키는 메서드

shouldComponentUpdate()

  • 리렌더링 여부 결정(기본값 true) true인 경우 : 리렌더링 진행 false인 경우 : 리렌더링 하지 않음
  • 함수형 컴포넌트에서 memo, useMemo, useCallback이 역할을 대신함
shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);
    return nextState.number % 10 !== 4; // 리렌더링x
  }

render()

  • 변경사항 반영이 다 되어 준비완료 되면 호출되는, 즉 렌더링 하는 메서드
  • DOM 에 변경사항이 반영됨

getSnapshotBeforeUpdate()

  • 컴포넌트에 변화가 일어나기 직전 DOM의 상태를 저장
  • componentDidUpdate 함수에서 사용하기 위한 스냅샷 형태의 데이터
getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("getSnapshotBeforeUpdate");
    if (prevProps.color !== this.props.color) {
      return this.myRef.style.color;
    }
    return null;
  }

componentDidUpdate()

  • 컴포넌트 업데이트 작업 완료 후 호출해 실제 화면에 반영됨
  • getSnapshotBeforeUpdate에서 반환한 값 조회 가능
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate", prevProps, prevState);
    if (snapshot) {
      console.log("업데이트 되기 직전 색상: ", snapshot);
    }
  }

3️⃣ Unmounting

컴포넌트가 DOM에서 제거되는 단계

componentWillUnmount()

  • 컴포넌트가 마운트 해제되어 DOM에서 제거되기 직전에 호출되는 메서드
  • 타이머 제거, 네트워크 요청 취소, componentDidMount() 내에서 생성된 구독 해제 등 작업 수행
componentWillUnmount() {
	clearInterval(this.timerID);
}

Fuction Component LifeCycle

React 16.8 버전 이후 도입된 React Hook을 통해 클래스 컴포넌트에서만 할 수 있던 state, lifecycle method 기능을 사용할 수 있게 됨

class vs function component lifecycle

분류클래스형 컴포넌트함수형 컴포넌트
Mountingconstructor()함수형 컴포넌트 내부
Mountingrender()return()
MountingcomponentDidMount()useEffect(()⇒{}, [])
UpdatingcomponentDidUpdate()useEffect(()⇒{}, [state1, state2])
UnMountingcomponentWillUnmount()useEffect(()⇒{ return () ⇒ { }}, [state1, state2])

참고

https://ko.legacy.reactjs.org/docs/state-and-lifecycle.html
https://react.vlpt.us/basic/25-lifecycle.html
https://leetrue-log.vercel.app/react-rendering-basic

profile
개발계발하는 프론트엔드 개발자🍠

0개의 댓글