ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • TIL-2024.04.29 - React - 005. Life Cycle Method
    > Frontend/React 2024. 4. 30. 22:25

     

     

    질문

    1. Life Cycle Method 가 머야?

    2. Life Cycle Method 의 종류에 대해 알려줘

     

     

     

     

    Life Cycle Method (생명 주기 메소드)

    - Lifecycle Method는 컴포넌트의 수명 주기 동안 발생하는 다양한 이벤트에 대응하여 코드를 실행할 수 있는 메소드들의 집합

    - 이러한 메소드들은 컴포넌트가 생성될 때, 업데이트될 때, 그리고 제거될 때 호출.

     

     

     

    컴포넌트의 라이프사이클 매서드

     

     

     

     

     1. 마운트(Mount) 단계

    - 마운트 단계는 컴포넌트가 DOM에 삽입되는 과정을 관리.

    - 주요 생명주기 메소드:
    - constructor(): 컴포넌트의 초기화를 위해 호출되어, 초기 state를 설정하거나 메소드를 바인딩하는 등의 작업을 수행.

    - static getDerivedStateFromProps(): props로부터 state를 동기적으로 업데이트할 때 사용되어,  props의 변화에 따라 state를 업데이트하는 데 사용.
    - render(): UI를 렌더링.

    - componentDidMount(): 컴포넌트가 마운트된 직후에 호출돼,  초기 데이터를 호출, 외부 라이브러리와의 통합, DOM 조작 등 수행

     

    2. 업데이트(Update) 단계

     

    - 업데이트 단계는 컴포넌트의 상태나 속성이 변경되었을 때 관리.
    - 주요 생명주기 메소드:
    - static getDerivedStateFromProps(): props로부터 state를 업데이트하는 데 사용.
    - shouldComponentUpdate(): (성능 최적화 목적으로) 컴포넌트의 업데이트를 결정하는 메소드.

    - render(): UI를 다시 렌더링.

    - getSnapshotBeforeUpdate(): DOM에 변화가 일어나기 직전에 호출되며, 이전의 DOM 상태를 기반으로 작업을 수행.

    - componentDidUpdate(): 컴포넌트가 업데이트된 직후에 호출돼,  이전 상태와 현재 상태를 비교하여 데이터를 가져오거나 외부 변경을 처리하는 등의 작업을 수행.

     

     

     

    3. 언마운트(Unmount) 단계

    - 언마운트 단계는 컴포넌트가 DOM에서 제거되는 과정을 관리.

    - 주요 생명주기 메소드:

    - componentWillUnmount(): 컴포넌트가 DOM에서 제거되기 직전에 호출되어  이벤트 리스너를 제거 | 타이머를 정리하는 등 수행.

     

     

     

    예제: 

    import React from 'react';
    
    class LifeCycleSample extends React.Component {
        state = {
            number: 0,
            color: null
        };
    
        myRef = null; // ref 설정 부분
    
    
        // constructor: 컴포넌트 처음 구성 시, 실행
        constructor(props) {
            super(props);
            console.log("constructor");
        }
    
        // getDerivedStateFromProps : 마운트 & 업데이트
        static getDerivedStateFromProps(nextProps, prevState) {
            console.log("getDerivedStateFromProps");
            if (nextProps.color !== prevState.color) {
                return {color: nextProps.color};
            }
            return null;
        }
    
        // componentDidMount : 첫 렌더링 마친 후, 실행
        componentDidMount() {
            console.log("componentDidMount");
    
        }
    
        // shouldComponentUpdate : 리렌더링 시작 여부 파악
        shouldComponentUpdate(nextProps, nextState, nextContext) {
            console.log("shouldComponentUpdate");
            return nextState.number % 10 !== 4;
        }
    
        // componentWillUnmount : 제거 시, 실행
        componentWillUnmount() {
            console.log("componentWillUnmount");
        }
    
        render() {
            return(
                <div>
    
                </div>
            )
        }
    }
    
    
    export default LifeCycleSample;

     

     

     

     

     

     

    댓글

Designed by Tistory.