React - Lifecycle

Enjoywater·2020년 9월 5일
0

TIL

목록 보기
15/33
post-thumbnail

React의 Component생명주기가 있다.
Component실행(mounting) / 업데이트 / 제거(unmounting) 될 때, 특정한 이벤트들이 발생하게 된다.

출처 - https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

단계에 따라서 아래에 나올 함수들이 순서대로 실행이 된다.



1. 실행 (mounting)

MountingelementDOM으로 넣는다는 것을 의미한다.


  • constructor()

Component시작될 때, 가장 먼저 호출되며 초기 state 및 기타 초기값을 설정한다.
argumentsprops를 사용하여 호출되며, super(props)먼저 호출하여 시작해야 한다.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

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

  • getDerivedStateFromProps()

DOM에서 element들을 랜더링하기 직전에 호출된다.
초기 props를 기반으로 state object를 설정하는 함수이다.
argumentsstate를 취하며, 변경된 state를 return한다.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  static getDerivedStateFromProps(props, state) {
    return {favoritecolor: props.favcol };
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header favcol="yellow"/>, document.getElementById('root'));

  • render()

render() 필수적으로 포함되어야하며 실제로 HTML을 DOM에 출력한다.

  • componentDidMount()

Component랜더링 된 후에 호출이 된다.
여기에서는, 이미 DOM에 있어야하는 코드를 실행한다.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

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


2. 업데이트

Componentstateprops가 변경 될 때마다 Component업데이트된다.


  • getDerivedStateFromProps()

Componentupdate될 때 호출되는 첫 번째 메소드이다.


  • shouldComponentUpdate()

React가 랜더링을 계속 해야하는지 여부를 지정하는 Boolean값을 return한다.
기본값은 true이며 false를 return하면 업데이트가 되지 않는다.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  shouldComponentUpdate() {
    return false; // true로 변경하면 코드가 정상적으로 동작한다.
  }
  changeColor = () => {
    this.setState({favoritecolor: "blue"});
  }
  render() {
    return (
      <div>
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
      <button type="button" onClick={this.changeColor}>Change color</button>
      </div>
    );
  }
}

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

run in codepen


  • render()

Component업데이트될 때, 변경사항이 있는 HTMLDOM다시 랜더링을 해야하므로 당연히 호출된다.


  • getSnapshotBeforeUpdate()

해당 메소드에서는 업데이트가 되기 전 stateprops접근할 수 있다.
사용할 때에는 componentDidUpdate() 메소드를 포함해야 하며, 그렇지 않으면 오류가 발생한다.


  • componentDidUpdate()

Component업데이트 된 후에 호출이 되는 메소드이다.



3. 제거 (unmounting)

ComponentDOM에서 제거되거나 React가 호출하는 대로 Unmounting된다.


  • componentWillUnmount()

ComponentDOM에서 제거되려고 할 때 호출이 되는 메소드이다.

profile
블로그 이전 👉🏻 enjoywater.tistory.com

0개의 댓글