React | 컴포넌트 라이트사이클

Chloe K·2022년 10월 5일
0
post-thumbnail

리액트에서 사용하는 component들은 라이프사이클 (생명주기)가 존재한다.
페이지가 렌더링되기 전인 준비과정에서 시작하여 페이지에서 사라질 때 끝난다.

❗️라이프사이클 메서드는 클래스형 컴포넌트에서만 사용이 가능하다. 함수형 컴포넌트에는 hook을 사용하여 비슷한 작업을 할 수 있다.

이 과정에서 라이프사이클은 크게 3단계로 나뉜다
1. Mount
2. Update
3. Unmount

1. Mount


마운트는 DOM이 생성되고 웹 브라우저상에 나타나는 것을 의미한다.
이 때 호출하는 메소드로는

  • constructor()
  • getDerivedStateFromProps
  • render () : UI를 렌더링하는 메소드
  • componentDidMount () : 컴포넌트가 웹 브라우저상에 나타난 후 호출하는 메서드

📌 DidWill의 차이점
Will은 어떤 작업을 작동하기 전에 실행되는 메서드이고,
Did은 어떤 작업을 작동한 후에 실행되는 메서드이다.

constructor ()

  • 클래스 생성자 메소드
  • 컴포넌트를 만들 때 처음으로 실행된다.

render ()

  • 필수 메서드
  • 리액트 요소를 반환한다.
render() {
    return (
       <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    )
  }

componentDidMount

  • 컴포넌트를 만들고, 첫 렌더링을 다 마친 후 실행된다.

2. Update


컴포넌트는 props 또는 state가 변경되면 업데이트가 발생한다.
+parent 컴포넌트가 리렌더링될 때
+this.forceUpdate로 강제로 렌더링을 트리거 할때

  • componentDidUpdate ()

componentDidUpdate ()

  • 컴포넌트의 리렌더링을 완료한 후에 실행된다.

3. Unmount


마운트의 반대과정으로 다른 페이지로 이동해서 더 이상 컴포넌트가 필요하지 않을 때와 같은 경우에 컴포넌트를 DOM에서 제거하는 것이다.

  • componentWillUnmount() : 컴포넌트가 웹 브라우저 상에서 사라지기 전에 호출하는 메서드

componentDidUnmout ()

  • 컴포넌트를 DOM에서 제거 할때 실행된다.

📒 예제

impor React from 'react';


class App extends React.Component {
  this.state = {
    count: 0
  };
  add = () => {
    this.setState(current => ({ count: current.count + 1 }));
  };
  minus = () => {
    this.setState(current => ({ count: current.count - 1 }));
  };

  componentDidMount() {
    console.log("Component rendered");
  }

  componentDidUpdate() {
    console.log("I just updated");
  }

  componentWillUnmount() {
    console.log("Good bye..")
  }

  render() {
    console.log("I'm rendering");
    
    return (
       <div>
        <h1>The number is: {this.state.count}</h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    )
  }
}

export default App;

💡콘솔

1. Mount

I'm rendering
component rendered

* render() 함수가 제일 먼저 호출되고, componentDidMount() 호출
2. Update 

state 변경 시 - add or minus 버튼 클릭해서 state 값이 변경될 때 console 

I'm rendering
I just updated


* setState()를 호출하면 컴포넌트를 호출하고, 먼저 render()를 호출한 다음 업데이트가 진행된 후 완료되면 componentDidUpdate 실행
3. Unmount

다른 페이지로 이동해서 더 이상 컴포넌트가 필요하지 않을 때

-> componentWillUnmount()가 호출된다. 

profile
Frontend Developer

0개의 댓글