리액트 - LifeCycle

아침7시개발·2021년 12월 30일
0

리액트

목록 보기
6/16

LifeCycle

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>
    );
  }
}

리액트 17부터는 componentWillMount, componentWillUpdate, componentWillReceiveProps 라이프 사이클이 deprecated 된다.

Mount

컴포넌트가 처음 실행될 때 그것을 Mount라고 표현한다. 컴포넌트가 시작되면 우선 context, defaultPropsstate를 저장한다. 그 후에 componentWillMount 메소드를 호출한다. 그리고 render로 컴포넌트를 DOM에 부착한 후 Mount가 완료된 후 componentDidMount가 호출된다.

주의할 점은, componentWillMount에서는 props나 state를 바꾸면 안 된다. Mount 중이기 때문이죠. 그리고 아직 DOM에 render하지 않았기 때문에 DOM에도 접근할 수 없다.

componentDidMount에서는 DOM에 접근할 수 있다. 그래서 여기에서는 주로 AJAX 요청을 하거나, setTimeout, setInterval같은 행동을 한다.

  1. state, context, defaultProps 저장
  2. componentWillMount
  3. render
  4. componentDidMount

Props Update

props가 업데이트될 때의 과정입니다. 업데이트되기 전에 업데이트가 발생하였음을 감지하고, componentWillReceiveProps 메소드가 호출된다. 그 후 shouldComponentUpdate, componentWillUpdate가 차례대로 호출된 후, 업데이트가 완료(render)되면 componentDidUpdate가 된다. 이 메소드들은 첫 번째 인자로 바뀔 props에 대한 정보를 가지고 있습니다. componentDidUpdate만 이미 업데이트되었기 때문에 바뀌기 이전의 props에 대한 정보를 가지고 있다.

shouldcomponentUpdate에서는 아직 render하기 전이기 때문에 return false를 하면 render을 취소할 수 있습니다. 주로 여기서 성능 최적화를 한다. 쓸데없는 update가 일어나면 여기서 걸러낸다.

주의사항이 있는데, componentWillUpdate에서는 state를 바꿔서는 안 된다. 아직 props도 업데이트하지 않았으므로 state를 바꾸면 또 shouldComponentUpdate가 발생한다. componentDidUpdate에서는 render이 완료되었기 때문에 DOM에 접근할 수 있다.

  1. componentWillReceiveProps
  2. shouldComponentUpdate
  3. componentWillUpdate
  4. render
  5. componentDidUpdate

State Update

setState 호출을 통해 state가 업데이트될 때의 과정이다. props update와 과정이 같지만, componentWillReceiveProps 메소드는 호출되지 않는다. 그리고 메소드의 두 번째 인자로는 바뀔 state에 대한 정보를 가지고 있다. componentDidUpdate는 두 번째 인자로 바뀌기 이전의 state에 대한 정보를 가지고 있다.

  1. shouldComponentUpdate
  2. componentWillUpdate
  3. render
  4. componentDidUpdate

Unmount

컴포넌트가 제거되는 것은 Unmount라고 표현한다. 더는 컴포넌트를 사용하지 않을 때 발생하는 이벤트가 있습니다. componentWillUnmount가 그것이다. componentDidUnmount는 없다. 이미 제거된 컴포넌트에서 이벤트를 발생시킬 수는 없다. componentWillMount에서 주로 연결했던 이벤트 리스너를 제거하는 등의 여러 가지 정리 활동을 한다.

  1. componentWillUnmount

Error

에러 발생 시를 위한 componentDidCatch도 있다. 리액트 16에서 추가되었다.

componentDidCatch(error, info) {
  console.error(error, info);
}

getDerivedStateFromProps

리액트 16에서 추가된 라이프사이클이다. props가 바뀌면 그에 따라 state도 같이 바꾼다. 예를 들어 props.a가 10이고 derivedA state를 props.a의 10배로 설정해두었다면 derivedState는 기본적으로 100이 된다. props.a가 11이 되었을 때 derivedA는 110으로 따라서 변경된다.

출처

https://www.zerocho.com/category/React/post/579b5ec26958781500ed9955

profile
쉬엄쉬엄하는 개발자

0개의 댓글