• 회원가입
  • 로그인
  • 구글아이디로 로그인

React - Lifecycle (컴포넌트 수명 주기)

1,013  
목차 

※ Lifecycle of Components (컴포넌트 수명주기)

 

React의 각 컴포넌트에는, 3가지 주요 단계에서 검사 및 조작 할 수있는 수명주기 존재. (즉, Mounting → Updating → Unmounting

 


Mounting (마운팅)

  1. [Mounting] 1. constructor() 메서드
  2. [Mounting] 2. getDerivedStateFromProps() 메서드
  3. [Mounting] 3. render() 메서드
  4. [Mounting] 4. componentDidMount() 메서드

Updating (업데이팅)

  1. [Updating] 1. getDerivedStateFromProps() 메서드
  2. [Updating] 2. shouldComponentUpdate() 메서드
  3. [Updating] 3. render() 메서드
  4. [Updating] 4. getSnapshotBeforeUpdate() 메서드
  5. [Updating] 5. componentDidUpdate() 메서드

Unmounting (언마운팅)

  1. [Unmounting] componentWillUnmount() 메서드

 

Mounting (마운팅)

 

1.

Mounting은 요소를 DOM에 넣는 걸 말함.

 

2.

React에는 컴포넌트를 마운트 할 때 아래 순서대로 호출되는 네 가지 내장 메서드 갖음.

 

・constructor()

・getDerivedStateFromProps()

render()

・componentDidMount()

 

3.

render() 메서드 : 필수. (= 항상 호출.)

나머지 메서드 : 선택. (= 정의 시 호출.)

 


[Mounting] 1. constructor() 메서드

 

1. 

constructor () 메서드는 컴포넌트 초기화 시 가장 먼저 호출되며, 초기 state 및 기타 초기값을 설정하는 곳임.

 

2.

constructor () 메서드는 인수로 props를 사용하여 호출되며, 항상 다른 것보다 먼저 super (props)를 호출하여 시작해야 함. 이렇게 하면 부모의 constructor() 메서드가 시작되고 컴포넌트가 부모 (= React.Component) 상속 가능해짐.

 

3. 예제

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  render() {

    return (

      <h1>{this.state.name} Homzzang.com</h1>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 


[Mounting] 2. getDerivedStateFromProps() 메서드

 

1.

getDerivedStateFromProps () 메서드는 DOM에서 요소를 렌더링하기 직전에 호출되며, 초기 Props 기반으로 state 객체를 설정하는 자연스러운 장소.

 

2.

getDerivedStateFromProps () 메서드는 state를 인수로 취하고, state가 변경된 객체를 반환.

 

3. 예제 (렌더링 전 변경: 홈짱닷컴 → 코딩강의)

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  static getDerivedStateFromProps(props, state) {

    return {name: props.rename };

  }

  render() {

    return (

      <h1>{this.state.name} Homzzang.com</h1>

    );

  }

}


ReactDOM.render(<Hz rename="코딩강의"/>, document.getElementById('root'));

 


[Mounting] 3. render() 메서드

 

1.

render() 메서드는 필수이며 실제로 HTML을 DOM에 출력시킴. 

 

2. 예제

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  render() {

    return (

      <h1>홈짱닷컴 Homzzang.com</h1>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 


[Mounting] 4. componentDidMount() 메서드

 

1.

componentDidMount () 메서드는 컴포넌트가 렌더링 된 후 호출되는데, 여기에서 컴포넌트가 이미 DOM에 배치되어 있음을 요하는 명령문을 실행함. (즉, 렌덩링 완료 후, 동적으로 새로 변경시킬 때 사용.)

 

2. 예제 (렌더링 후 변경: 홈짱닷컴 → 코딩강의)

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  componentDidMount() {

    setTimeout(() => {

      this.setState({name: "코딩강의"})

    }, 1000)

  }

  render() {

    return (

      <h1>{this.state.name} Homzzang.com</h1>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 

 

Updating (업데이팅)

 

1.

수명 주기의 다음 단계는 컴포넌트가 업데이트 되는 시기로.

컴포넌트의 state 또는 Props가 변경 될 때마다 컴포넌트가 업데이트 됨.

 

2.

React에는 컴포넌트가 업데이트 될 때 다음 순서로 호출되는 5 개의 내장 메서드가 존재.

 

1. getDerivedStateFromProps()

2. shouldComponentUpdate()

3. render()

4. getSnapshotBeforeUpdate()

5. componentDidUpdate()

 

3.

render() 메서드 : 필수. (= 항상 호출.)

나머지 메서드 : 선택. (= 정의 시 호출.)

 


[Updating] 1. getDerivedStateFromProps() 메서드

 

1.

getDerivedStateFromProps 메서드는 컴포넌트가 업데이트 될 때 호출되는 첫 번째 메서드로서, (※ 선택 사항이라 정의된 경우에 호출됨.)

초기 Props 기반으로 state 객체를 설정하는 여전히 자연스러운 장소임.

 

2. 예제

아래 예제 경우, (홈짱닷컴 → 코딩강의)로 변경하는 코드가 있지만getDerivedStateFromProps () 메서드가 호출되어 rename 속성의 속성값으로 업데이트 하므로 최종 결과는 '그누강의'가 됨.

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  static getDerivedStateFromProps(props, state) {

    return {name: props.rename };

  }

  changeName = () => {

    this.setState({name: "코딩강의"});

  }

  render() {

    return (

      <div>

      <h1>{this.state.name} Homzzang.com</h1>

      <button type="button" onClick={this.changeName}>Change name</button>

      </div>

    );

  }

}


ReactDOM.render(<Hz rename="그누강의"/>, document.getElementById('root')); 

 


[Updating] 2. shouldComponentUpdate() 메서드

 

1. 

shouldComponentUpdate() 메서드에서 React가 렌더링을 계속해야하는지 여부를 지정하는 참거짓 반환 가능. 

true - 업데이트 시 컴포넌트 렌더링 계속. (기본값)

false - 업데이트 시 컴포넌트 렌더링 중지.

 

 

2-1. 예제 - false이면 렌더링 중지. ∴ '홈짱닷컴' 출력.


import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  shouldComponentUpdate() {

    return false;

  }

  changeName = () => {

    this.setState({name: "코딩강의"});

  }

  render() {

    return (

      <div>

      <h1>{this.state.name} Homzzang.com</h1>

      <button type="button" onClick={this.changeName}>Change name</button>

      </div>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));


 

2-2. 예제 - true이면, 렌더링 계속. ∴ '코딩강의' 출력.

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  shouldComponentUpdate() {

    return true;

  }

  changeName = () => {

    this.setState({name: "코딩강의"});

  }

  render() {

    return (

      <div>

      <h1>{this.state.name} Homzzang.com</h1>

      <button type="button" onClick={this.changeName}>Change name</button>

      </div>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 


[Updating] 3. render() 메서드

 

1.

render() 메서드는 컴포넌트가 업데이트 될 때도 당연히 호출되며, 새로운 변경 사항으로 HTML을 DOM에 다시 렌더링해야 함.


2. 예제 - (버튼 클릭 시, 변환: 홈짱닷컴 → 코딩강의) 

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  changeName = () => {

    this.setState({name: "코딩강의"});

  }

  render() {

    return (

      <div>

      <h1>{this.state.name} Homzzang.com</h1>

      <button type="button" onClick={this.changeName}>Change name</button>

      </div>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 


[Updating] 4. getSnapshotBeforeUpdate() 메서드

 

1.

getSnapshotBeforeUpdate() 메서드에서 업데이트 전 상태와 Props에 접근 가능함. 즉, 업데이트 후에도 업데이트 전에 값이 무엇인지 확인 가능함.


2.

getSnapshotBeforeUpdate() 메서드가 있는 경우,  componentDidUpdate () 메서드도 포함해야 함. 

그렇지 않으면 오류가 발생함.


3. 예제.

컴포넌트가 마운트 될 때는 "홈짱닷컴"으로 렌더링 됨.

Props가 장착되면 타이머가 state를 변경하고 1초 후에 이름이 "코딩강의"가 됨.


이 작업은 업데이트 단계를 트리거하고 이 컴포넌트에는 getSnapshotBeforeUpdate() 메서드가 있으므로 이 메서드가 실행되고 빈 DIV1 요소에 메시지를 씀.

그런 다음, 

componentDidUpdate() 메서드가 실행되고 빈 DIV2 요소에 메시지를 씀.

 

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  componentDidMount() {

    setTimeout(() => {

      this.setState({name: "코딩강의"})

    }, 1000)

  }

  getSnapshotBeforeUpdate(prevProps, prevState) {

    document.getElementById("div1").innerHTML =

    "업데이트 전 이름: " + prevState.name;

  }

  componentDidUpdate() {

    document.getElementById("div2").innerHTML =

    "업데이트 후 이름: " + this.state.name;

  }

  render() {

    return (

      <div>

      <h1>{this.state.name} Homzzang.com</h1>

      <div id="div1"></div>

      <div id="div2"></div>

      </div>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 


[Updating] 5. componentDidUpdate() 메서드

 

1.

componentDidUpdate 메서드는 DOM에서 컴포넌트가 업데이트 된 후 호출됨. (즉, 업데이트가 DOM에서 렌더링 된 후 호출됨.)

 

2. 예제. (업데이트 렌더링 후 변환: 홈짱닷컴 → 코딩강의)

컴포넌트가 마운트 될 때 name이 "홈짱닷컴"으로 렌더링 됨.

컴포넌트가 마운트되면 타이머가 state 변경하고 name이 "코딩강의"가 됨. 

이 행위는 업데이트 단계를 트리거하며, 이 컴포넌트에는 componentDidUpdate() 메서드가 있으므로 이 메서드가 실행되고 빈 DIV 요소에 메시지를 씀.

 

 

import React from 'react';

import ReactDOM from 'react-dom';


class Hz extends React.Component {

  constructor(props) {

    super(props);

    this.state = {name: "홈짱닷컴"};

  }

  componentDidMount() {

    setTimeout(() => {

      this.setState({name: "코딩강의"})

    }, 1000)

  }

  componentDidUpdate() {

    document.getElementById("demo").innerHTML = 

"업데이트 후 이름 : " + this.state.name;

  }

  render() {

    return (

      <div>

      <h1>{this.state.name} Homzzang.com</h1>

      <div id="demo"></div>

      </div>

    );

  }

}


ReactDOM.render(<Hz />, document.getElementById('root'));

 

 

Unmounting (언마운팅)

 

1.

라이프 사이클의 다음 단계는 컴포넌트가 DOM에서 제거되거나 React가 호출하는 대로 마운트 해제하는 것임.

 

2.

 

React에는 컴포넌트를 마운트 해제할 때 호출되는 기본 제공 메서드가 componentWillUnmount() 메서드 하나 뿐임.

 


[Unmounting] componentWillUnmount() 메서드

 

1. 

componentWillUnmount 메서드는 컴포넌트가 DOM에서 제거되려고 할 때 호출됨.

 

2. 예제 - (버튼 클릭 시 Hz 컴포넌트가 DOM에서 제거되려하며 이 때 componentWillUnmount 메서드가 실행됨.)

 

import React from 'react';

import ReactDOM from 'react-dom';


class Box extends React.Component {

  constructor(props) {

    super(props);

    this.state = {show: true};

  }

  delHz = () => {

    this.setState({show: false});

  }

  render() {

    let hz;

    if (this.state.show) {

      hz = <Hz />;

    };

    return (

      <div>

        {hz}

        <button type="button" onClick={this.delHz}>Delete Hz</button>

      </div>

    );

  }

}


class Hz extends React.Component {

  componentWillUnmount() {

    alert("'Hz' 컴포넌트가 마운트 해제됩니다.");

  }

  render() {

    return (

      <h1>홈짱닷컴 Homzzang.com</h1>

    );

  }

}


ReactDOM.render(<Box />, document.getElementById('root'));

 



제목
React - Home (입문) + 사용 환경 구축
React - Intro (소개) - 작동 방식 + 역사
React - Start (시작) - 사용환경 설정.
React - ES6 (최신 JS의 3가지 주요 이슈)
React - Render HTML (웹페이지 렌더링)
React - JSX (= JavaScript XML)
React - Components (컴포넌트) ★
React - Props (인수 = 독립변수) ★
React - State (상태 객체) ★
React - Lifecycle (컴포넌트 수명 주기)
React - Events (이벤트) ★★
React - Forms (입력폼) ★★★
React - CSS (스타일링)
React - Sass (SCSS)
목록
찾아주셔서 감사합니다. Since 2012