[React] 생명주기 (LifeCycle)

HD.·2022년 6월 1일
0

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

리액트에서 컴포넌트는 라이프사이클 즉, 컴포넌트의 수명 주기가 존재한다. 그리고 각 수명 주기마다 실행할 수 있는 메서들가 존재하는데 이를 LifeCycle Method라고 하고 위의 그림에서 볼 수 있다.

LifeCycle은 크게 생성 될때(마운트), 업데이트 될때(업데이트), 사라질 때(언마운트)이렇게 3부분으로 나눌 수 있다.

Mounting (마운트)

Mounting이란 컴포넌트가 생성되고 DOM에 적용되는 것을 의미한다.
리액트는 마운트 단계에서 4가지 메소드를 제공하고 아래의 순서대로 호출 된다.
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()

render() 메소드는 필수 메소드이고 나머지 메소드는 필요할 때 사용하면 된다.

1. constructor

constructor는 컴포넌트의 생성자 메서드로 컴포넌트가 만들어지면 가장 먼저 실행되는 메서드이다. 이 메서드에서 초기 state를 정할 수 있다.

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'));

2. getDerivedStateFromProps

getDerivedStateFromProps 메서드는 렌더링 직전에 호출 된다. 주로 props로 받은 것을 state에 넣어줄 때 사용한다.

특정 객체를 반환하게 되면 해당 객체 안에 있는 내용들이 컴포넌트의 state로 설정이 됩니다.

참고로 이 메서드는 컴포넌트가 처음 렌더링 되기 전에도 호출 되고, 그 이후 리렌더링 되기 전에도 매번 실행됩니다.

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'));

3. render

필수 메서드이며 실제로 컴포넌트를 렌더링하는 메서드이다.

class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

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

4. componentDidMount

componentDidMount() 메서드는 컴포넌트가 렌더링된 후 호출된다. 여기서 주로 DOM을 사용하는 외부 라이브러리를 연동하거나, ajax요청, 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'));

Updating (업데이트)

컴포넌트의 업데이트가 일어나는 요인은 다음과 같다.

  • props가 바뀔 때
  • state가 바뀔 때
  • 부모 컴포넌트가 리렌더링 될 때
  • this.forceUpdate로 강제 렌더링 시킬 때

업데이트 단계에서 5가지 메소드를 제공하고 아래의 순서대로 호출 된다.

  1. getDerivedStateFromProps()
  2. shouldComponentUpdate()
  3. render()
  4. getSnapshotBeforeUpdate()
  5. componentDidUpdate()

1. getDerivedStateFromProps

마운트 단계에서 알아본 메서드이고 업데이트 단계에서도 호출 된다.

2. shouldComponentUpdate

shouldComponentUpdate() 메서드는 React가 렌더링을 계속할지 여부를 지정하는 Boolean 값을 반환할 수 있다. 기본값은 true이다.
이 메서드는 성능 최적화를 위해 사용된다.

  shouldComponentUpdate(nextProps, nextState) {
    console.log("shouldComponentUpdate", nextProps, nextState);
    // 숫자의 마지막 자리가 4면 리렌더링하지 않습니다
    return nextState.number % 10 !== 4;
  }

3. render

새로운 변경사항을 다시 그려주기위해 render() 메서드가 호출 된다.

4. getSnapshotBeforeUpdate

getSnapshotBeforeUpdate() 메서드에서 업데이트 이전의 props 및 state에 접근할 수 있다. 즉, 업데이트 후에도 업데이트 이전의 값을 확인할 수 있다.
getSnapshotBeforeUpdate() 메서드를 사용했을 경우 componentDidUpdate()메서드도 포함 되어야한다. 그렇지 않으면 오류가 발생한다.
실제 사용 사례는 아래 링크에서 확인 가능하다.
https://codesandbox.io/s/getsnapshotbeforeupdate-yeje-vpmle?fontsize=14&file=/src/ScrollBox.js

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

5. componentDidUpdate

마운트단계에서 처럼 componentDidUpdate() 메서드는 랜더링이 된 후에 호출된다. 또한 3번째 파라미터로 getSnapshotBeforeUpdate에서 반환한 값을 조회할 수 있다.

componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("componentDidUpdate", prevProps, prevState);
    if (snapshot) {
      console.log("업데이트 되기 직전 색상: ", snapshot);
    }
  }

Unmounting (언마운트)

언마운트 단계는 컴포넌트가 DOM에서 사라지는 것을 의미한다.
리액트에서는 언마운트 단계에서 단 한개의 메서드를 제공한다.

  • componentWillUnmount()

1. componentWillUnmount

componentWillUnmount() 메소드는 컴포넌트가 DOM에서 제거되려고 할 때 호출된다. 주로 clearTimeout이나 외부 사용한 외부라이브러리에 dispose 기능이 있다면 여기서 호출한다.

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




참고

https://www.w3schools.com/react/react_lifecycle.asp
https://react.vlpt.us/basic/25-lifecycle.html
https://kyun2da.dev/react/%EB%A6%AC%EC%95%A1%ED%8A%B8-%EB%9D%BC%EC%9D%B4%ED%94%84%EC%82%AC%EC%9D%B4%ED%81%B4%EC%9D%98-%EC%9D%B4%ED%95%B4/

profile
즐거워야코딩

0개의 댓글

관련 채용 정보