20201004 TIL Component Lifecycle

ToastEggsToast·2020년 10월 4일
0

React

목록 보기
3/13

Component LifeCycle?

Each component has several “lifecycle methods” that you can override to run code at particular times in the process. You can use this lifecycle diagram as a cheat sheet. In the list below, commonly used lifecycle methods are marked as bold. The rest of them exist for relatively rare use cases.
from. React Official Page

리액트의 Component가 생성되고, 업데이트 되고, 제거되는 과정에서 더 다양한 UI 등을 제공하기 위해 LifeCycleMethod를 사용할 수 있다.
해당 메소드들은 "Class Component에서만 사용이 가능"하고, Functional Component에서는 비슷한 구현을 위해 "Hooks"를 이용하게 된다.

라이프 사이클 메소드를 세세하게 보자면, 이 이상 다양한 메소드들을 확인 가능하지만 가장 크게 분리하면 이렇게 5가지로 분리가 된다.

Render

The render() method is the only required method in a class component

render은 Component가 존재하는 한 "절대적으로 발생되는" 루틴이다. (not optional)
render 과정 이후 Component의 jsx, 즉 콘텐츠가 웹 페이지 스크린에 보여지게 된다.

componentDidMount

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

맨 처음 component가 스크린에 등장할 때 "딱 한번만" 실행가능한 메소드이다.

componentDidUpdate

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Component에 업데이트가 생길 때 사용 가능하고, 맨 처음 Component가 render될 때에는 부를 수 없다. (즉, 컴포넌트가 스크린에 출력되고 그 이후 업데이트가 존재할 경우에 사용 가능함. Automatically, all the time when component update their states.)

import React from "react";
import ReactDOM from "react-dom";
// import SeasonDisplay from "./SeasonDisplay";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = { lat: null, errorMessage: "" };
    window.navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          lat: position.coords.latitude,
        });
      },
      (err) => {
        this.setState({ errorMessage: err.message });
      }
    );
  }
  componentDidMount() {
    console.log("my component was rendered to the screen");
  }
  componentDidUpdate() {
    console.log("my component was just updated - it rerendered");
  }
  render() {
    if (this.state.errorMessage && !this.state.lat) {
      return <div>Error: {this.state.errorMessage}</div>;
    }
    if (!this.state.errorMessage && this.state.lat) {
      return <div>Latitude: {this.state.lat}</div>;
    }
    if (!this.state.errorMessage && !this.state.lat) {
      return <div>Loading...</div>;
    }
  }
}

ReactDOM.render(<App />, document.querySelector("#root"));

React App을 실행시키면 => DidMount의 console, DidUpdate의 console이 순서대로 출력된다.

-- 정리 --

ComponentDidMount -> Loading화면을 만들기에 적합함.
ComponentDidUpdate -> Component에 변화가 일어났을 경우
ComponentWillUnmount -> Good place to do cleanup (especially for non-React stuff) 스크린에서 component를 지울 경우, 리액트와 관련된 것들이 아닌 것들에 사용하기 좋다.....?

그 외
-> shouldComponentUpdate
-> getDerivedStateFromProps
-> getSnapsholtBeforeUpdate

profile
개발하는 반숙계란 / 하고싶은 공부를 합니다. 목적은 흥미입니다.

0개의 댓글