LifeCycle

sese·2022년 10월 6일

새싹

목록 보기
21/39

[ 라이프 사이클 이란? ]

  • 컴포넌트의 수명 주기
  • 모든 리액트 컴포넌트에 존재한다.


[ 마운트(Mount) ]

DOM이 생성되고 웹 브라우저상에 나타나는 것

  • constructor()
  • render()
  • componentDidMount()

[ 업데이트(Update) ]

Props나 state가 바뀌었을 때 업데이트한는 것

  • componentDidUpdate(props, state)

[ 언마운트(Unmount) ]

컴포넌트가 화면에서 사라질(제거될) 때

  • componentWillUnmount()

예시

import React, { Component } from 'react';

class LifeCycle extends Component {
    constructor(props) {
        super(props);

        this.state = {
            name: '1',
            age: 1
        }
    }

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

    componentDidUpdate(props, state) {
        console.log('componentDidUpdate');
        console.log('props : ', props);
        console.log('state : ', state);
        console.log('this.state : ', this.state);
        // age값이 변경되었을 때만 실행하기
        if ( state.age != this.state.age ) {
            console.log('age change');
        }
    }

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

    render() {
        return (
            <div>
                라이프사이클 {this.state.name}
                <button onClick={() => {this.setState({name: 'hi'})}}>버튼</button>
                <button onClick={() => {this.setState({age: 2})}}>버튼</button>
            </div>
        )
    }
}

export default LifeCycle;
profile
예전 글은 다크모드로 봐야 잘 보일 수도 있습니다.

0개의 댓글