[React] 라이프사이클

hellow_coding·2024년 6월 9일

React 라이프사이클은 컴포넌트가 생성되고 업데이트되며, 제거되는 일련의 단계를 의미합니다. 각 단계에서 특정 메서드가 호출되며, 이를 통해 컴포넌트의 상태나 다른 작업을 수행할 수 있습니다.

1. 마운트(Mounting)

마운트 단계는 컴포넌트가 처음 DOM에 삽입될 때(실행) 발생합니다. 이 단계에는 다음 네 가지 메서드가 호출됩니다.

  • constructor()
    컴포넌트가 생성될 때 호출됩니다.
    초기 상태와 메서드 바인딩을 설정하는 데 사용됩니다.
constructor(props) {
  super(props);
  this.state = { count: 0 };
}
  • static getDerivedStateFromProps(props, state)
    컴포넌트가 생성되거나 업데이트될 때 호출됩니다.
    주어진 props로부터 상태를 업데이트해야 할 때 사용됩니다.
static getDerivedStateFromProps(props, state) {
  if (props.someValue !== state.someValue) {
    return { someValue: props.someValue };
  }
  return null;
}
  • render()
    컴포넌트의 UI를 정의하는 메서드입니다.
    이 메서드는 반드시 순수 함수여야 하며, 상태나 props를 변경하지 않아야 합니다.
render() {
  return <div>{this.state.count}</div>;
}
  • componentDidMount()
    컴포넌트가 처음 렌더링되고 난 후에 호출됩니다.
    여기서 AJAX 요청이나 DOM 노드에 대한 직접적인 작업을 수행할 수 있습니다.
componentDidMount() {
  // 데이터 로드 또는 타이머 설정 등
}

2. 업데이트(Updating)

업데이트 단계는 컴포넌트가 새로운 props를 받거나 상태가 변경될 때 발생합니다. 이 단계에는 다음 여섯 가지 메서드가 호출될 수 있습니다.

  • static getDerivedStateFromProps(props, state)
    컴포넌트가 업데이트될 때도 호출됩니다.
    props로부터 상태를 업데이트할 필요가 있을 때 사용됩니다.

  • shouldComponentUpdate(nextProps, nextState)
    컴포넌트가 업데이트될지 여부를 결정합니다.
    성능 최적화를 위해 사용할 수 있습니다.

shouldComponentUpdate(nextProps, nextState) {
  return nextState.count !== this.state.count;
}
  • render()
    컴포넌트의 UI를 다시 정의합니다.

  • getSnapshotBeforeUpdate(prevProps, prevState)
    DOM이 변경되기 직전에 호출됩니다.
    여기서 반환된 값은 componentDidUpdate로 전달됩니다.

getSnapshotBeforeUpdate(prevProps, prevState) {
  if (prevState.count < this.state.count) {
    return { scrollPosition: window.scrollY };
  }
  return null;
}
  • componentDidUpdate(prevProps, prevState, snapshot)
    컴포넌트가 업데이트된 후에 호출됩니다.
    getSnapshotBeforeUpdate에서 반환된 값에 접근할 수 있습니다.
componentDidUpdate(prevProps, prevState, snapshot) {
  if (snapshot !== null) {
    window.scrollTo(0, snapshot.scrollPosition);
  }
}

3. 언마운트(Unmounting)

언마운트 단계는 컴포넌트가 DOM에서 제거될 때 발생합니다. 이 단계에는 한 가지 메서드가 호출됩니다.

  • componentWillUnmount()
    컴포넌트가 DOM에서 제거되기 직전에 호출됩니다.
    타이머 정리, 구독 해제 등의 작업을 수행합니다.
componentWillUnmount() {
  // 타이머 정리 또는 구독 해제 등
}


  • 라이프사이클 흐름
    constructor -> render -> componentDidMount ->
    (번튼 누른 후) increase function -> render -> componentDidUpdate
    (조건 충족) increase function -> render -> end -> componentDidUpdate
import React, { Component } from "react";
import { render } from "@testing-library/react";
import BoxClass from "./BoxClass";

export default class AppClass extends Component {
  constructor(props) {
    super(props);

    // 상태를 한번에 선언
    this.state = {
      count: 0,
      num: 1,
      value: 0,
    };

    console.log("constructor");
  }

  increase = () => {
    this.setState((prevState) => ({
      count: prevState.count + 1,
      value: prevState.value + 2,
    }));
    console.log("increase function", this.state);
  };

  componentDidMount() {
    // api 콜
    console.log("componentDidMount");
  }

  componentDidUpdate() {
    console.log("componentDidUpdate", this.state);
  }

  render() {
    console.log("render");

    return (
      <>
        <div>state : {this.state.count}</div>
        <button onClick={this.increase}>버튼</button>

        {this.state.count < 3 && <BoxClass num={this.state.value} />}
      </>
    );
  }
}
import React, { Component } from "react";

export default class BoxClass extends Component {
  componentWillUnmount() {
    console.log("end");
  }

  render() {
    return (
      <div>
        <div>value : {this.props.num}</div>
      </div>
    );
  }
}

요약

React 라이프사이클 메서드는 컴포넌트의 생성, 업데이트, 제거 단계에서 특정 작업을 수행할 수 있도록 도와줍니다. 이를 통해 컴포넌트의 상태를 관리하고, DOM과 상호작용하며, 성능을 최적화할 수 있습니다.

이러한 메서드는 주로 클래스 컴포넌트에서 사용되지만, 함수형 컴포넌트에서는 React 훅스(Hooks)를 사용하여 비슷한 기능을 구현할 수 있습니다. 예를 들어, useEffect 훅은 componentDidMount, componentDidUpdate, componentWillUnmount를 결합한 역할을 합니다.

profile
꿈많은 개발자

0개의 댓글