7장 - 컴포넌트의 라이프사이클 메서드

sh·2022년 8월 3일
0

모든 리액트 컴포넌트에는 라이프사이클(수명 주기)이 존재한다.
컴포넌트의 수명은 페이지에 렌더링되기 전인 준비 과정에서 시작하여 페이지에서 사라질 때 끝난다.

라이프사이클 메서드는 클래스형 컴포넌트에서만 사용 가능하다. 함수형 컴포넌트에서는 Hooks 기능을 사용해 비슷한 작업을 처리할 수 있다.

라이프사이클 메서드의 이해

라이프사이클 메서드의 종류는 총 아홉 가지이다.
Will접두사가 붙은 메서드는 어떤 작업을 작동하기 에 실행, Did가 붙은 메서드는 어떤 작업을 작동한 에 실행되는 메서드

라이프 사이클은 마운트, 업데이트, 언마운트 카테고리로 나눈다.

마운트

DOM이 생성되고 웹 브라우저상에 나타나는 것을 마운트(mount)라고 한다.

  • constructor : 컴포넌트를 새로 만들 때마다 호출되는 클래스 생성자 메서드

  • getDerivedStateFromProps: props에 있는 값을 state에 넣을 때 사용하는 메서드

  • render: 준비한 UI를 렌더링하는 메서드

  • componentDidMount: 컴포넌트가 웹 브라우저상에 나타난 후 호출하는 메서드

업데이트

컴포넌트가 업데이트되는 경우

  1. props가 바뀔 때
  2. state가 바뀔 때
  3. 부모 컴포넌트가 리렌더링될 때
  4. this.forceUpdate로 강제로 렌더링을 트리거할 때
  • getDerivedStateFromProps: 마운트 과정에서도 호출되며, 업데이트가 시작하기 전에도 호출된다. props의 변화에 따라 state 값에도 변화를 주고 싶을 때 사용한다.

  • shouldComponentUpdate: 컴포넌트가 리렌더링을 해야 할지 말아야 할지를 결정하는 메서드
    이 메서드에서는 true 혹은 false 값을 반환한다.
    - true를 반환하면 다음 라이프사이클 메서드를 계속 실행
    - false를 반환하면 작업을 중지한다. (컴포넌트가 리렌더링되지 않는다.)
    만약 특정 함수에서 this.forceUpdate()함수를 호출하면 이 과정을 생략하고 바로 render 함수를 호출한다.

  • render: 컴포넌트를 리렌더링한다.

  • getSnapshotBeforeUpdate: 컴포넌트 변화를 DOM에 반영하기 바로 직전에 호출하는 메서드

  • componentDidUpdate: 컴포넌트의 업데이트 작업이 끝난 후 호출하는 메서드

언마운트

컴포넌트를 DOM에서 제거하는 것을 언마운트(unmount)라 한다.

  • componentWillUnmount: 컴포넌트가 웹 브라우저상에서 사라지기 전에 호출하는 메서드

라이프사이클 메서드 살펴보기

render

render() { ... }
라이프사이클 메서드 중 유일한 필수 메서드이며 컴포넌트 모양새를 정의한다.

이 메서드 안에서 this.props와 this.state에 접근할 수 있으며 리액트 요소를 반환한다.

이 메서드 안에서는 이벤트 설정이 아닌 곳에서 setState를 사용하면 안 되며, 브라우저의 DOM에 접근해서도 안 된다. DOM 정보를 가져오거나 state에 변화를 줄 때는 componentDidMount에서 처리해야 한다.

constructor

constructor(props) { ... }
컴포넌트를 만들 때 처음으로 실행된다. 초기 state를 정할 수 있다.

getDerivedStateFromProps

v16.3 이후에 새로 만든 라이프사이클 메서드
props로 받아 온 값을 state에 동기화시키는 용도로 사용하며, 컴포넌트가 마운트될 때와 업데이트될 때 호출된다.

static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.value !== prevState.value){
    return { value: nextProps.value };
  }
  return null; // state를 변경할 필요가 없다면 null 반환
}

componentDidMount

componentDidMount() { ... }

컴포넌트를 만들고, 첫 렌더링을 다 마친후 실행한다.
이 함수 안에서 다른 자바스크립트 라이브러리 또는 프레임워크의 함수를 호출하거나 이벤트 등록, setTimeout, setInterval, 네트워크 요청 같은 비동기 작업을 처리하면 된다.

shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState) { ... }

props 또는 state를 변경했을 때 리렌더링을 시작할지 여부를 지정하는 메서드
반드시 true 혹은 false 값을 반환해야 한다. 컴포넌트를 만들 때 이 메서드를 따로 생성하지 않으면 기본적으로 true 값을 반환한다.

이 메서드 안에서 현재 props와 state는 this.propsthis.state로 접근하고, 새로 설정될 props 또는 state는 nextPropsnextState로 접근할 수 있다.

getSnapshotBeforeUpdate

v16.3 이후 만든 메서드
render에서 만들어진 결과물이 브라우저에 실제로 반영되기 직전에 호출된다.
이 메서드에서 반환하는 값은 componentDidUpdate에서 세 번째 파라미터인 snapshot 값으로 전달받을 수 있다.
주로 업데이트하기 직전의 값을 참고할 일이 있을 때 활용된다. (예: 스크롤바 위치 유지)

getSnapshotBeforeUpdate(prevProps, prevState) {
  if(prevState.array !== this.state.array) {
    const { scrollTop, scrollHeight } = this.list
    return { scrollTop, scrollHeight };
  }
}

componentDidUpdate

componentDidUpdate(prevProps, prevState, snapshot) { ... }

리렌더링을 완료한 후 실행한다. 업데이트가 끝난 직후이므로 DOM 관련 처리를 해도 무방하다.

componentWillUnmount

componentWillUnmount() { ... }

컴포넌트를 DOM에서 제거할 때 실행한다. componentDidMount에서 등록한 이벤트, 타이머, 직접 생성한 DOM이 있다면 여기서 제거 작업을 해야 한다.

componentDidCatch

v16에서 새로 도입되었으며, 컴포넌트 렌더링 도중에 에러가 발생했을 때 애플리케이션이 먹통이 되지 않고 오류 UI를 보여 줄 수 있게 해준다.

componentDidCatch(error, info) {
  this.setState({
    error: true
  });
  console.log({ error, info });
}

error는 파라미터에 어떤 에러가 발생했는지 알려 주며, info 파라미터는 어디에 있는 코드에서 오류가 발생했는지에 대한 정보를 준다.

이 메서드를 사용할 때는 컴포넌트 자신에게 발생하는 에러를 잡아낼 수 없고 자신의 this.props.children으로 전달되는 컴포넌트에서 발생하는 에러만 잡아낼 수 있다.


라이프사이클 메서드 사용하기

예제 컴포넌트

import React, { Component } from "react";

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

  myRef = null;

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

  static getDerivedStateFromProps(nextProps, prevState) {
    console.log("getDerivedStateFromProps");
    if (nextProps.color !== prevState.color) {
      return { color: nextProps.color };
    }
    return 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,
    });
  };

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

  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;

import { Component } from "react";
import LifeCycleSample from "./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>
    );
  }
}

export default App;
  • 랜덤 색상 버튼 클릭 후
  • 더하기 버튼 클릭 후

정리

라이프사이클 메서드는 컴포넌트 상태에 변화가 있을 때마다 실행하는 메서드
서드파티 라이브러리를 사용하거나 DOM을 직접 건드려야 하는 상황에서 유용하다.

0개의 댓글