ReactJS

[ReactJS] 리액트 생명주기

2022. 11. 10.

생명주기: component의 생성, 변경, 소멸 과정을 뜻함

component: 특정 코드 뭉치를 다른 부분에 이식하거나 재 사용하기 위해 사용하는 코드 블록 단위

  • component 생성 함수
    • render()
    • constructor()
    • getDerivedStateFromProps()
    • componentDidMount()

 

contructor(props)

    • 컴포넌트가 실행될 때 가장 먼저 호출되는 함수
    • 생명주기 함수 중 가장 먼저 실행됨
    • 처음 한 번만 호출됨
    • 그리고 state를 정의하거나 state에 초기값을 넣고 싶을 때 이 함수 안에 작성하면 됨
    • 또한 이 함수는 파라미터값으로 props가 들어가며, 함수 내부에 super(props)를 먼저 작성해야 함
    • The constructor in a React component is called before the component is mounted.
      • mount
        • 컴포넌트에서 작성한 요소를 DOM에 넣어 확인하는 것
        • 이 mount에 관련된 함수가 render(), constructor(), getDerivedStateFormProps(), componentDidMount()임
    • When you implement the constructor for a React component, you need to call super(props) method before any other statement.
    • If you do not call super(props) method, this.props will be undefined in the constructor and can lead to bugs.
  • In React, constructors are mainly used for two purposes:
    1. It used for initializing the local state of the component by assigning an object to this.state.
    2. It used for binding event handler methods that occur in your component.
      1. bind 개념 > https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
      2. bind 활용 > https://siosio3103.medium.com/react-binding-어떤-방식을-써야할가-be5894ba1dae



예제 코드

import React, { Component } from "react";

class R005_LifecycleEx extends Component {
    constructor(props) {
        super(props);
        this.state = {};
        console.log('1. constructor Call')
    }
    
    render() {
        console.log('3. render Call')
        return(
            <h2>[THIS IS CONSTRUCTOR FUNCTION]</h2>
        )
    }
}

export default R005_LifecycleEx;

위 component를 App.js에 import하여 render하였을 때 constructor()가 제일 먼저 실행되므로 1. constructor Call이 콘솔에 가장 먼저 뜨는 것을 확인할 수 있다

 

`getDerivedStateFromProps(props, state)`

  • 컴퍼넌트가 새로운 props를 받게 되었을 때 state를 변경해줌
  • constructor( ) 함수 다음으로 실행된다
  • App.js에서 전달한 prop_value라는 변수를 props.prop_value로 접근해 값 가져옴

  • 보다시피 constructor > getDerived > render 순으로 실행되었다.

 

`componentDidMount( )`

  • 생명주기 함수들 중에서 가장 마지막에 실행됨
  • render( ) 함수가 코드를 화면에 그려준 후 실행됨
  • 화면 그려지는 것이 끝난 후의 이벤트 처리, 초기화 등 가장 많이 활용되는 함수임

 

 

`shouldComponentUpdate()`

  • 생명주기 과정 중 component의 변경(props, state) 과정에 속하는 함수임
  • state 변경이 일어나면 실행됨
    • boolean 유형의 데이터를 반환함
      • return 값이 true면 render( ) 함수를 한 번 더 호출함
  • setState( ) 함수는 변수의 선언과 초기화를 동시에 실행함