본문 바로가기
스터디 열기

(참고) 클래스 컴포넌트

클래스 컴포넌트에서 확인하는 생명주기입니다. 클래스 컴포넌트는 지금도 동작하지만 새 코드에는 권하지 않습니다. 그래도 옛 코드를 읽을 때 자주 만나고, 에러 경계(Error Boundary)는 아직 클래스 컴포넌트로만 만들 수 있어서 알아 둘 만합니다. 다음 절에서 같은 시점들을 함수 컴포넌트가 어떻게 다루는지 비교해 보세요.

컴포넌트의 생명주기는 크게 세 가지로 나눌 수 있습니다.

  1. 마운트(mount)
  2. 업데이트(update)
  3. 언마운트(unmount)

마운트(mount) - 처음 컴포넌트가 나타났을 때

처음 state와 props를 가지고 컴포넌트를 생성합니다.

  • constructor
  • getDerivedStateFromProps
  • render
  • componentDidMount

업데이트(update) - 컴포넌트 상태값이 바뀔 때

마운트가 완전히 완료된 후 상태값이나 prop의 변화가 생겼을 때, 리액트는 이를 감지하고 컴포넌트에 업데이트해줍니다.

  • getDerivedStateFromProps
  • shouldComponentUpdate
  • render
  • getSnapshotBeforeUpdate
  • componentDidUpdate

shouldComponentUpdate는 문 역할을 합니다. false를 돌려주면 render를 부르지 않고 이번 업데이트를 건너뜁니다. 이 메서드를 정의하지 않으면 항상 업데이트하고, 정의했다면 true나 false를 돌려줘야 합니다. 아래 예제는 true를 돌려줍니다. getDerivedStateFromProps와 getSnapshotBeforeUpdate는 쓸 일이 거의 없어서 아래 예제에서도 쓰지 않습니다.

언마운트(unmount) - 컴포넌트가 사라질 때

언마운트에서는 componentWillUnmount가 실행됩니다. 컴포넌트를 완전히 DOM에서 제거하는 시점입니다.

  • componentWillUnmount : 컴포넌트가 사라지기 바로 직전에 호출됩니다.

위 목록을 그림으로 보면 아래와 같습니다. 파랑 칸은 화면에 무엇을 그릴지 정하는 렌더 단계이고, 갈색 칸은 그 결과를 DOM에 반영하는 커밋 단계입니다. 대부분 DOM에 반영한 뒤에 부르지만, getSnapshotBeforeUpdate는 DOM이 바뀌기 직전에, componentWillUnmount는 DOM에서 제거되기 직전에 부릅니다. 업데이트에서 shouldComponentUpdate가 false이면 render부터 뒤가 모두 건너뛰어집니다.

이 그림에는 옛 메서드 componentWillMount(마운트에서 render 앞)와 componentWillUpdate(업데이트에서 shouldComponentUpdate와 render 사이)가 빠져 있습니다. 아래 예제가 이 옛 메서드를 쓰기 때문에 로그에는 나타납니다. 이름이 바뀐 사정은 아래 상자에서 설명합니다.

import React, { Component } from 'react';

class ClassComp extends Component {
  constructor(props) {
    super(props);
    this.state = { number: 0 };
  }

  componentWillMount() {
    //컴포넌트가 생성될 때 실행됩니다. (렌더링 되기 이전)
    console.log('componentWillMount');
  }

  componentDidMount() {
    //마운트가 완료되고 나서 실행됩니다. (렌더링 이후)
    console.log('componentDidMount');
  }

  shouldComponentUpdate(nextProps, nextState) {
    //상태 업데이트가 되고 컴포넌트가 업데이트 되기 전(렌더되기 전) 실행됩니다.
    //초기 렌더링에서 발생하지 않습니다.
    console.log('shouldComponentUpdate');
    return true;
  }

  componentWillUpdate(nextProps, nextState) {
    // 새 이름은 UNSAFE_componentWillUpdate(). 옛 이름도 React 19에서 실행되지만 개발 모드에서 경고가 뜹니다.
    //초기 렌더링에서 발생하지 않고, 그 이후 업데이트가 되고 나서 발생합니다.
    console.log('componentWillUpdate');
  }

  componentDidUpdate(nextProps, nextState) {
    //업데이트가 되고 나서 실행됩니다.
    console.log('componentDidUpdate');
  }

  componentWillUnmount() {
    //컴포넌트가 제거되기 바로 직전에 실행됩니다.
    console.log('componentWillUnmount');
  }

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

  render() {
    console.log('render');
    return (
      <div>
        <button onClick={this.handleClick}>Click me!</button>
        <span>{this.state.number}</span>
      </div>
    );
  }
}

class App extends Component {
  render() {
    return <ClassComp />;
  }
}

export default App;

클래스 컴포넌트가 처음 보인다면 두 가지만 짚고 갑니다. this.state는 함수 컴포넌트의 useState 값, this.setState는 그 값을 바꾸는 함수에 해당합니다. handleClick = () => { ... }처럼 클래스 안에 쓴 화살표 함수는 this가 이 컴포넌트를 가리키게 해서, onClick에 넘겨도 this.setState를 부를 수 있게 합니다.

이 예제를 실행했을 때의 콘솔 출력은 다음과 같습니다. 이 책은 3.1 2.4처럼 StrictMode를 뺀 main.jsx를 기준으로 하며, Vite 기본 템플릿 그대로 켜 둔 StrictMode에서는 로그가 달라집니다(아래 상자).

처음 페이지를 열었다면, 어떻게 출력될까요?

componentWillMount
render
componentDidMount

componentWillMount가 먼저 실행되고 render된 뒤 componentDidMount로 마운트를 마칩니다. (옛 메서드 componentWillMount가 render 앞에 오는 점을 그림과 견줘 보세요.)

이번에는 button을 클릭하여 출력을 확인해 봅시다.

shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

기존 출력에 shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate 네 줄이 추가되었습니다.

다시 한 번 버튼을 눌러봅시다. 이번에는 어떻게 되었나요?

이번에도 이전에 버튼 눌렀을 때와 마찬가지로 shouldComponentUpdate, componentWillUpdate, render, componentDidUpdate가 출력됩니다. 업데이트는 상태가 바뀔 때마다 이 순서로 반복됩니다.

언마운트도 확인해 보겠습니다. 위 예제에서는 ClassComp가 사라지는 일이 없어서 componentWillUnmount가 찍히지 않습니다. App을 아래처럼 바꾸면 버튼으로 ClassComp를 없애고 다시 나타나게 할 수 있습니다.

class App extends Component {
  state = { show: true };

  render() {
    return (
      <div>
        <button onClick={() => this.setState((s) => ({ show: !s.show }))}>
          보이기/숨기기
        </button>
        {this.state.show && <ClassComp />}
      </div>
    );
  }
}

보이기/숨기기를 눌러 ClassComp를 숨기는 순간 콘솔에 componentWillUnmount가 찍힙니다. 함수 컴포넌트에서 같은 시점을 확인하는 방법은 8.2의 3.3에서 이어집니다.

옛 메서드 이름과 경고

componentWillMount, componentWillReceiveProps, componentWillUpdate 세 메서드는 사용이 권장되지 않습니다. React 16.3에서 UNSAFE_ 접두사가 붙은 이름으로 바뀌었고, 접두사 없는 이름을 쓰면 개발 모드에서 경고가 뜹니다. componentDidMount는 이 세 가지에 들지 않으며 지금도 클래스 컴포넌트에서 정상적으로 쓰는 메서드입니다.

위 ClassComp 코드를 React 19.3.1에서 그대로 실행하면 옛 이름도 아직 실행되지만, 콘솔에 다음과 같은 경고가 함께 찍힙니다.

componentWillMount
render
(경고) componentWillMount has been renamed, and is not recommended for use. ...
(경고) componentWillUpdate has been renamed, and is not recommended for use. ...
componentDidMount
--- 버튼 클릭 ---
shouldComponentUpdate
componentWillUpdate
render
componentDidUpdate

경고는 componentWillMount를 UNSAFE_componentWillMount로 바꾸거나, 부수 효과는 componentDidMount로 옮기라고 안내합니다. 버튼을 누른 뒤의 순서에서 componentWillUpdate가 render보다 먼저 실행되는 것도 확인할 수 있습니다.

StrictMode를 켜 둔 경우: Vite가 만든 main.jsx처럼 <StrictMode>로 감싼 개발 모드에서는 render가 두 번씩 찍힙니다. 마운트 직후에는 componentDidMount, componentWillUnmount, componentDidMount가 차례로 찍히고, 버튼을 누를 때마다 shouldComponentUpdate도 두 번 찍힙니다. React가 부수 효과를 일찍 찾아내려고 일부러 한 번 더 실행하는 것이며 배포(프로덕션)에서는 한 번씩만 실행됩니다. 자세한 설명은 6.3 useEffect에 있습니다.

정리해보겠습니다.

처음 페이지를 열면 마운트 단계가 한 번 일어나고 componentDidMount로 끝납니다. 같은 컴포넌트가 계속 화면에 있는 동안에는 마운트가 다시 일어나지 않습니다. 위에서 본 것처럼 없앴다가 다시 나타내면 새로 마운트합니다.

현재 버튼을 클릭하면 number 숫자가 1씩 증가하도록 미리 설정하였습니다. 버튼을 클릭하면 상태가 바뀌고 리액트는 업데이트 단계를 진행합니다. 이때 render()는 컴포넌트 전체를 다시 부르고, 그 결과를 이전과 견주어 바뀐 부분만 실제 DOM에 반영합니다. 이것이 위에서 보았던 상황들입니다.


React class vs function style - 4.1. 클래스에서 라이프 사이클 구현 하기 React class vs function style - 4.2.1. 함수에서 라이프 사이클 구현 하기 - 실습준비

마지막 수정