티스토리 뷰

모든 컴포넌트는 생명주기 메서드를 가지며, 크게 마운트(mount) / 업데이트(update) / 언마운트(unmount) 의 개념으로 구분됩니다.

아래 생명주기 도표를 참고하면서, 생명주기 메서드에 대해서 알아보겠습니다.

컴포넌트 생명주기 - 기본
컴포넌트 생명주기 - 상세

 

 

render( )

클래스 컴포넌트 생성 시, 필수로 생성해야 하는 메서드로 호출될때마다 동일한 결과를 반환해야 하며, 브라우저와 직접적인 상호작용을 하지 않습니다.

 

 

constructor( )

생성자로 컴포넌트 생성시 처음 실행됩니다.

단, 바인딩, state 초기화 작업이 없다면, 생성하지 않아도 됩니다.

( * 메서드 생성 시, super(props)를 반드시 정의 해줘야 합니다.)

 

 

getDerivedStateFromProps( )

컴포넌트를 마운트할 때와 업데이트 할때 render 메서드 호출 직전에 호출됩니다. 

 

 

componentDidMount( )

컴포넌트 생성 후,  마운트된 직후 호출되기 때문에, DOM 초기작업을 비롯한 비동기 작업을 처리해주면 됩니다.

 

 

shouldComponentUpdate( )

props 또는 state 변경했을 때,렌더링 수행 여부를 결정하는 메서드입니다. 

결과값은 true / false 값을 반환해야하며, 기본값은 true입니다

 

 

getSnapshotBeforeUpdate( )

최종 렌더링된 결과 DOM 반영되었을 때 호출되는데, 실제 브라우저에 반영되기 직전에 호출된다.

 

 

componentDidUpdate( )

최초 렌더링 이후, 컴포넌트 갱신이 일어난 직후 호출됩니다.

컴포넌트가 갱신이 된 직후이기 때문에, DOM 조작을 위해 활용하는게 좋습ㄴ디ㅏ.

 

 

componentWillUnmount( )

컴포넌트 마운트가 해제되어, 제거할때 호출합니다.

 

 

componentDidCatch( )

오류 발생 시, 호출합니다.

 

 

예제

기본 컴포넌트 작성 후, 콘솔창을 확인하면 다음과 같은 순서로 메서드가 호출되는것을 확인할 수 있다.

  • constructor( )
  • render( )
  • componentDidMount( )
import React, { Component } from 'react';

class ComponentLifeCycle extends Component {

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

    static getDerivedFromProps(nextProps, prevState){
        console.log('getDerivedFromProps()');
    }

    componentDidMount(){
        console.log('componentDidMount()');
    }
    
    shouldComponentUpdate(nextProps, prevState){
        console.log('shouldComponentUpdate()');
    }
    
    componentWillUnmount(){
        console.log('componentWillUnmount()');
    }
    
    getSnapshotBeforeUpdate(prevProps, prevSate){
        console.log('getSnapshotBeforeUpdate()');
    }

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

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

        return (
            <div>
                
            </div>
        );
    }
}

export default ComponentLifeCycle;

 


* 출처

ko.reactjs.org - React.component [바로가기]

댓글