React

React 라이프사이클

테라시아 2024. 12. 15. 21:40

리액트 라이프사이클
    페이지에 컴포넌트가 생성되고, 수정되고, 사라지는 순서를 의미한다.
    React 에서 클래스 컴포넌트를 사용하면, 9개의 메서드를 통해 작업의 흐름을 제어할 수 있다.

    - 전체적인 흐름
    마운트 -> 업데이트 -> 언마운트

마운트(Mount)
    페이지에 컴포넌트가 나타나는 것

    - constructor : 새로운 컴포넌트를 생성할 때 마다 자동으로 실행되는 특별한 메서드
    - getDerivedStateFromPorps : prop를 state에 넣을 때 사용한다. 컴포넌트와 마운트 될 때 와 업데이트 될 때 실행된다.
    - render : 준비해놓은 UI를 랜더링할 때 사용된다.
    - componentDidMount : 페이지에 컴포넌트가 나타난 후 실행된다.

업데이트(Update)
    - props 값에 변화가 있을 때
    - state 값에 변화가 있을 때
    - 부모 컴포넌트가 리랜더링 될 때
    - forceUpdate() 를 사용해서 강제로 리랜더링을 할 때(사용 X, 상태관리가 잘못된 구조다.)

    - 1, 2, 3에 따른 변화가 있을 때 아래가 실행이 된다.

    render : 컴포넌트 리랜더링
    - shouldComponentUpdate : 다음 라이프사이클 메서드를 이동할지 멈출지를 결정한다.
    - getSnapshotBeforeUpdate : 컴포넌트 업데이트 직전에 실행
    - componentDidUpdate : 컴포넌트 업데이트 후에 실행

언마운트(Unmount)
    - 컴포넌트가 페이지에서 사라지는 것
    - componentwillUnmoint : 컴포넌트가 페이지에서 사라지기 직전에 실행된다.

 

☆ Code

 

★ LifeCycleContainer

const getRandomColor = () => {
    return "#" + Math.floor(Math.random() * 16777215).toString(16)
}

class LifeCycleContainer extends Component {

    state = {
        color: "#000000"
    }

    onClickToChangeColor = () => {
        this.setState({
            color: getRandomColor()
        })
        console.log(this.state.color)
    }

    render() {
        return (
            <div>
                <button onClick={this.onClickToChangeColor}>색상 변경</button>
                <LifeCycleComponent color={this.state.color}/>
            </div>
        );
    }
}

export default LifeCycleContainer;

 

★ LifeCycleComponent

import React, { Component } from 'react';


class LifeCycleComponent extends Component {
    state = {
        number : 0,
        color : null,
    }

    onClickToIncrease = () => {
        this.setState({
            number: this.state.number + 1
        })
    }

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

    static getDerivedStateFromProps(nextProps, prevState){
        console.log("getDerivedStateFromProps", nextProps, prevState)
        if(nextProps.color !== prevState.color){
            return {color:nextProps.color}
        }
        return null;
    }

    componentDidMount(){
        console.log("componentDidMount 실행 완료!")
    }

    shouldComponentUpdate(nextProps, nextState){
        console.log("shouldComponentUpdate", nextProps, nextState)
        return nextState.number % 5 !== 0
    }

    colorRef = null;

    getSnapshotBeforeUpdate(prevProps, prevState){
        console.log("getSnapshotBeforeUpdate", prevProps, prevState)
        if(prevProps.color !== this.props.color){
            return this.colorRef.style.backgroundColor;
        }
        return null;
    }

    componentDidUpdate(prevProps, prevState, snapshot){
        if(prevState){
            console.log(`업데이트 직전 State: ${prevState}`);
        }
        if(prevProps){
            console.log(`업데이트 직전 props: ${prevProps}`);
        }
        console.log("snapshot", snapshot);
    }


    render() {
        return (
            <div>
                <div
                    ref={(el) => this.colorRef = el}
                    style={{
                        width: "100px",
                        height: "100px",
                        backgroundColor : this.state.color,
                        display: "flex",
                        justifyContent : "center",
                        alignItems : "center",
                        color : "#fff"
                    }}
                >
                    <h1>{this.state.number}</h1>
                </div>

                <button onClick={this.onClickToIncrease}>더하기 버튼</button>
            </div>
        );
    }
}

export default LifeCycleComponent;

'React' 카테고리의 다른 글

React useMemo, useCallback  (1) 2024.12.16
React 사이드이펙트  (0) 2024.12.16
React 레퍼런스 실습  (0) 2024.12.11
React 레퍼런스  (0) 2024.12.10
React 상태  (0) 2024.12.09