Language/React

[React] 라이프사이클 메서드

jaewpark 2021. 10. 27. 15:40

라이프사이클 메서드의 종류는 총 아홉 가지

마운트, 업데이트, 언마운트 카테고리로 나눌 수 있다.

 

마운트

DOM이 생성되고 웹 브라우저상에 나타나는 것

 

업데이트

아래의 네 가지 경우에 발생

  • props가 바뀔때
  • state가 바뀔때
  • 부모 컴포넌트가 리렌더링될 때
  • this.forceUpdate로 강제로 렌더링을 트리거할 때

 

언마운트

마운트의 반대, 컴포넌트를 DOM에서 제거

 


 

라이프사이클 메서드

 

render() 함수

  • 컴포넌트 모양새를 정의하며, 유일한 필수 메서드
  • this.props와 this.state 접근 가능, 리액트 요소를 반환
  • 요소의 경우는 <div>같은 태그따로 선언한 컴포넌트, null값이나 false값 반환

 

constructor 메서드

  • 생성자 메서드, 초기 state를 정할 수 있다.

 

getDerivedStateFromProps 메서드

  • props로 받아 온 값을 state에 동기화시키는 용도로 사용
  • 컴포넌트가 마운트될 때와 업데이트될 때 호출
  • 리액스 v16.3 새로 만들어진 라이프사이클 메서드

 

componentDidMount 메서드

  • 컴포넌트를 만들고 첫 렌더링을 다 마친 후 실행
  • 다른 자바스크립트 라이브러리 또는 프레임 워크의 함수를 호출, 이벤트 등록 비동기 작럽을 처리

 

shouldComponentUpdate 메서드

  • props 또는 state 변경했을 때, 리렌더링을 시작할지 여부를 지정
  • 반드시 true값 또는 false값 반환
  • 따로 생성하지 않으면 기본적으로 true값 반환
  • false 반환 시 업데이트 과정 중지

 

getSnapshotBeforeUpdate 메서드

  • render에서 만들어진 결과물이 브라우저에 실제 반영되기 직전에 호출
  • 업데이트하기 직전의 값을 참고할 일이 있을 때 활용(스크롤바 위치 유지)

 

componentDidUpdate 메서드

  • 리렌더링 완료후 실행
  • 업데이트가 끝난 직후이기에 DOM 관련 처리 가능
  • prevProps 또는 prevState를 사용하여 이전에 가졌던 데이터에 접근 가능

 

componentWillUnmount 메서드

  • 컴포넌트를 DOM에서 제거할 때 실행

 

componentDidCatch 메서드

  • 컴포넌트 렌더링 도중에 에러가 발생했을 때, 오류 UI 보여줄 수 있게 해준다.

 


 

import React, { Component } from "react";

class LifeCycleSample extends Component {
  state = {
    number: 0,
    color: null,
  };

  myRef = null;

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

  // props 값을 state 동시화 시키는 용도
  // 부모에게서 받은 color 값을 state에 동기화
  static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.color !== prevState.color) {
      return { color: nextProps.color };
    }
    return null; // 변경할 필요가 없을 시 null 반환
  }

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

  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);

    return nextState.number % 10 !== 4; //숫자 마지막자리 4면 리렌더링 안함
  }

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

  handleClick = () => {
    this.setState({
      number: this.state.number + 1,
    });
  };

  // DOM에 변화가 일어나기 직전의 색상 속성을 snapshot 값으로 반환
  getSnapshotBeforeUpdate(prevProps, prevState) {
    console.log("getSnapShotBeforeUpdate");

    if (prevProps.color !== this.props.color) {
      return this.myRef.style.color;
    }
    return null;
  }

  // snapshot(getSnapshotBeforeUpdate 메서드에서 반환되는) 값을 조회
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate", prevProps, prevState);
    if (snapshot) {
      console.log("업데이트 되기 직전 색상: ", snapshot);
    }
  }

  render() {
    console.log("render");
    const style = {
      color: this.props.color,
    };

    return (
      <div>
        <h1 style={style} ref={(ref) => (this.myRef = ref)}>
          {this.state.number}
        </h1>
        <p>color: {this.state.color}</p>
        <button onClick={this.handleClick}>더하기</button>
      </div>
    );
  }
}

export default LifeCycleSample;
function getRandomColor() {
  return "#" + Math.floor(Math.random() * 16777215).toString(16);
}

class App extends Component {
  state = {
    color: "#000000",
  };

  handleClick = () => {
    this.setState({
      color: getRandomColor(),
    });
  };
  
    render() {
    return (
      <div>
        <button onClick={this.handleClick}>랜덤 색상</button>
        <LifeCycleSample color={this.state.color} />
      </div>
    );
  }
}

라이프사이클 메서드 흐름도