React Life Cycle

SangJin·2020년 1월 11일
0

React

목록 보기
1/1

리액트 라이프 사이클

1. 라이프 사이클 이벤트

  리액트는 일정한 생명주기를 가진다. 생명주기란 컴포넌트가 생성되고 소멸될때 까지의 주기를 일컫는다.
이 과정에서 특정시점에 발동되는 이벤트가 있는데 이런 이벤트를 라이프 사이클 이벤트 라고 한다. (ex:componentDidMount, render...)

2. 흐름

위 그림처럼 기본적인 전체 흐름이다.

하나하나 알아보도록 하자.

2-1. constructor

constructor(props){
  super(props)
  console.log('Constructor');

  생성자 메소드로서 컴포넌트가 처음 만들어질때 생성된다.

2-2. componentWillMount

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

  컴포넌트가 DOM 위에 만들어지기 전에 실행된다.

2-3. render

render(){
  return(
    <div>
    	render
   </div>
   )

  컴포넌트 렌더링을 담당한다.

2-4. componentDidMount

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

  컴포넌트가 만들어지고 첫 렌더링을 다 마친 후 실행되는 메소드
 이 안에서 JS프레임워크를 연동하거나, setTimeout, setInterval 및 AJAX,axios 등을 넣는다.
 활용도가 매우 높다.

2-5. componentWillReceiveProps

componentWillReceiveProps(nextProps){
    console.log("componentWillReceiveProps: " + JSON.stringify(nextProps));
}

컴포넌트가 prop을 새로 받았을 때 실행된다.
prop에 따라 state를 업데이트를 해야할 때 사용하면 유용하다.
이 안에서 this.setState()를 해도 추가적으로 렌더링하지 않는다.

2-6. shouldComponentUpdate

shouldComponentUpdate(nextProps, nextState){
    console.log("shouldComponentUpdate: " + JSON.stringify(nextProps) + " " + JSON.stringify(nextState));
    return true;

prop혹은 state가 변경 되었을 때, 렌더링 할지 말지 정하는 메소드.

2-7. componentWillUpeate

componentWillUpdate(nextProps, nextState){
    console.log("componentWillUpdate: " + JSON.stringify(nextProps) + " " + JSON.stringify(nextState));
}

컴포넌트가 업데이트 되기 전에 실행된다.

2-8. componentDidUpdate

componentDidUpdate(prevProps, prevState){
    console.log("componentDidUpdate: " + JSON.stringify(prevProps) + " " + JSON.stringify(prevState));
}

컴포넌트가 리렌더링을 마친 후 실행된다.

2-9. componentWillUnmount

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

컴포넌트가 DOM에서 사라진 후 실행되는 메소드

참조 : https://velopert.com/

profile
Developer

0개의 댓글