TIL (2020. 05 .27)

Shin Yeongjae·2020년 5월 27일
0

TIL

목록 보기
11/21
post-thumbnail

리액트 라이프사이클 이벤트

라이프사이클 이벤트는 무엇일까?

React의 컴포넌트는 생명주기(life cycle)을 가지고 있다. 생명주기란 컴포넌트가 생성되고 사용되고 소멸될 때 까지의 과정을 말한다.
이런 생명주기 안에서는 특정 시점에 자동으로 호출되는 메서드들이 있는데, 이것들을 라이프사이클 이벤트라고 한다.

간단하게 constructor, componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, componentWillUnmount, render 정도만 짚고 넘어가겠다.

React 공식문서에 시계예제가 있는데 매우 직관적이니 참고하면 좋다.

라이프사이클 이벤트의 종류

class Content extends React.Component {
  constructor(props) {
    super(props);
  }
  componentWillMount() {
    console.log('Component WILL MOUNT!')
  }
  componentDidMount() {
    console.log('Component DID MOUNT!')
  }
  componentWillReceiveProps(nextProps) {    
    console.log('Component WILL RECIEVE PROPS!')
  }
  shouldComponentUpdate(nextProps, nextState) {
    return true;
  }
  componentWillUpdate(nextProps, nextState) {
    console.log('Component WILL UPDATE!');
  }
  componentDidUpdate(prevProps, prevState) {
    console.log('Component DID UPDATE!')
  }
  componentWillUnmount() {
    console.log('Component WILL UNMOUNT!')
  }
  render() {
    return (
        <div>
          <h1>{this.props.sentDigit}</h1>
        </div>
    );
  }
}

constructor

constructor(props) {
  super(props);
}

생성자 메서드로 컴포넌트가 생성될 때 단 한번만 실행된다.
이 메서드에서만 state설정이 가능하다.

componentWillMount

componentWillMount() {
  console.log('Component WILL MOUNT!')
}

React 엘리먼트를 실제 DOM 노드에 추가하기 직전에 호출되는 메서드이다.
DOM이 생성되지 않았으니 DOM을 조작할 수 없고, render가 호출되기 전이기 때문에 setState를 사용해도 render가 호출되지 않는다.

render

컴포넌트 렌더링을 담당하는 메서드이다.

componentDidMount

componentDidMount() {
  console.log('Component DID MOUNT!')
}

컴포넌트가 만들어지고 render가 호출된 이후에 호출되는 메서드이다.
AJAX 통신이나 타이머를 생성하는 코드를 작성하는 부분이다.

componentWillReceiveProps

componentWillReceiveProps(nextProps) {
  console.log('Component Will Receive Props: ' + JSON.stringify(nextProps));
}

컴포넌트 생성 후 첫 렌더링을 마친 후 호출되는 메서드이다.
컴포넌트가 처음 마운트되는 시점에서는 호출되지 않는다.
props를 받아서 state를 변경해야 하는 경우 유용하게 쓰인다.
이 메서드 내부에서 setState를 사용해도 추가적인 렌더링이 발생하지 않는다.

shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState) {
  console.log('Should Component Update: ' + JSON.stringify(nextProps) + ' ' + JSON.stringify(nextState));
}

shouldComponentUpdate가 불린 이후에 컴포넌트 업데이트 직전에 호출되는 메서드이다.
새로운 props 또는 state가 반영되기 직전 새로운 값들을 받는다.
이 메서드 안에서 this.setState()를 사용하면 무한루프가 발생하니 주의해야 한다.

componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  console.log('Component Did Update: ' + JSON.stringify(prevProps) + ' ' + JSON.stringify(prevState));
}

컴포넌트 업데이트 직후에 호출되는 메서드이다.

componentWillUnmount

componentWillUnmount() {
  console.log('Component Will Unmount')
}

컴포넌트가 소멸된 시점에(DOM에서 삭제된 후) 실행되는 메서드이다.
컴포넌트 내부에서 타이머나 비동기 API를 사용하고 있을 때, 이를 제거할 때 유용하게 쓰인다.

ref

LifceCycle API
React 공식문서 시계 예제

profile
문과생의 개발자 도전기

0개의 댓글