[React] Class형 컴포넌트의 라이프사이클(Life Cycle)

박경호·2022년 4월 21일
0

리액트 개념정리

목록 보기
1/1

📢 이 문서는 다른 블로그의 글을 보강하여 작성된 문서입니다.

참고 및 출처 : React의 생명주기(Life Cycle) - zerocho.com


들어가며

  • 리액트에는 생명주기(Life Cycle)가 있습니다.
  • 필요한 순간을 캐치하여 원하는 동작을 만들 수 있게 됩니다.
  • 리액트 컴포넌트에는 클래스형과 함수형이 있는데 이 글에서는 클래스형 컴포넌트에 대해 다룹니다.

본문

도식화


예시 코드

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export default class Basic extends Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    birth: PropTypes.number.isRequired,
    lang: PropTypes.string,
  };

  static defaultProps = {
    lang: 'Javascript',
  };

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  state = {
    hidden: false,
  };

  componentWillMount() {
    console.log('componentWillMount');
  }

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

  componentWillReceiveProps(nextProps) {
    console.log('componentWillReceiveProps');
  }

  shouldComponentUpdate(nextProps, nextState) {
    console.log('shouldComponentUpdate');
    return true / false;
  }

  componentWillUpdate(nextProps, nextState) {
    console.log('componentWillUpdate');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('componentDidUpdate');
  }

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

  onClickButton = () => {
    this.setState({ hidden: true });
    this.refs.hide.disabled = true;
  }

  render() {
    return (
      <div>
        <span>저는 {this.props.lang} 전문 {this.props.name}입니다!</span>
        {!this.state.hidden && <span>{this.props.birth}년에 태어났습니다.</span>}
        <button onClick={this.onClickButton} ref="hide">숨기기</button>
        <button onClick={this.context.router.goBack}>뒤로</button>
      </div>
    );
  }
}

🔌 Mount

컴포넌트가 DOM에 장착되는 것

  1. 저장 ――― state, context, defaultProps 의 정보를 저장
  2. componentWillMount ――― 컴포넌트가 장착될 예정입니다
  3. render ――― 1번에서 받은 정보로 엘리먼츠를 다 그렸습니다
  4. componentDidMount ――― 정상적으로 장착되었습니다, DOM 접근 가능한 단계구요

🔨 Props Update (1/2)

업데이트 원인: Props가 변경됨을 감지함

  1. componentWillReceiveProps ――― props를 받을 예정입니다
  2. shouldComponentUpdate ――― 컴포넌트를 업데이트 해야합니다
  3. componentWillUpdate ――― 컴포넌트가 업데이트 될 예정입니다
  4. re-render ――― 엘리먼츠가 다시 그려졌습니다
  5. componentDidUpdate ――― 업데이트 완료 + 👀 이전 props를 알고있습니다

🔨 State Update (2/2)

업데이트 원인: State가 변경됨을 감지함

  1. shouldComponentUpdate ――― 컴포넌트를 업데이트 해야합니다
  2. componentWillUpdate ――― 컴포넌트가 업데이트 될 예정입니다
  3. render ――― 엘리먼츠가 다시 그려졌습니다
  4. componentDidUpdate ――― 업데이트 완료

🩸 UnMount

컴포넌트가 DOM에서 제거되는 것

  1. componentWillUnmount ――― 제거예정 "이 다음 사이클은 없어요, 제거된 후 이벤트 발생할 수 없으니까요"

⚙ Error

리액트 16 버전에서 추가되었고 에러발생을 감지하기 위해 생겨났어요

componentDidCatch(error, info) {
  console.error(error, info);
}
profile
안녕하세요 나는 개발자 👨‍💻

0개의 댓글