[기술면접] lifecycle

huni_·2022년 7월 2일
0

React

목록 보기
56/57
post-thumbnail

모든 것들은 하나의 주기를 따라갑니다. 우리는 태어나고, 성장하고 죽습니다. 거의 대부분은 일생의 이 주기를 따라가며, React Component도 마찬가지 입니다. Component는 만들어지고(Mounted on DOM), 업데이트를 통해 성장하며, 그리고 죽습니다(Unmounted on DOM). 이를 Component의 생명주기라고 합니다.

Component 수명의 단계마다 React가 제공하는 다양한 생명주기 메서드가 있습니다. React는 Component의 단계에 따라 자동으로 메서드를 호출합니다. 이 메서드들을 통해 Component를 컨트롤 할 수 있고, 단계에 따라 쉽게 다룰 수 있습니다.

현재 우리는 수명주기 메서드가 무엇이고, 왜 중요한지를 알아보았습니다. 그러면 생명주기의 다양한 메서드는 어떤 것들이 있을까요? 한번 살펴봅시다.

Lifecycle Methods

Component의 생명주기는 대체적으로 네가지 파트로 구분되어 있습니다.

1. Initialization

2. Mounting

3. Updating

4. Unmounting

각각의 단계마다 사용되는 생명주기 메서드에 대해 한번 알아봅시다.

Initialization

Component가 state와 props가 설정됨에 따라 여행을 시작하는 단계입니다. 보통은 생성자 메서드에서 끝나게 됩니다.

(아래 코드를 보시면 좀 더 쉽게 이해할 수 있습니다.)

class Initialize extends React.Component {
constructor(props)
{
// Calling the constructor of
// Parent Class React.Component
super(props);
// initialization process
this.state = {
   date : new Date(),
   clickedStatus: false
 };
}

Mounting

Mounting은 React component가 DOM에 달라붙는 단계입니다. (i.e 만들어지고, DOM에 삽입되는 단계)

이 단계는 Initialization 단계가 끝난 후 일어납니다. 여기서는 Component가 처음으로 rendering 됩니다. 이 단계에 속해있는 메서드는 다음과 같습니다.

1. componentWillMount()

이 메서드는 Component가 DOM에 탑재되거나 render 메서드가 호출되기 직전에 호출됩니다. 메서드가 호출된 이후 Component는 DOM에 탑재됩니다.

꼭 알아야할 점: render 메서드가 호출되기 전에 이 메서드는 호출되기 때문에 API 호출이나 this.setState를 이용하여 데이터를 수정하는 로직은 만들지 않는 것이 좋습니다. 아직 DOM에 탑재되지 않았기 때문데 API 응답과 함께 수정된 데이터가 반영되지 않을 것입니다. 그러므로 아무것도 state의 업데이트를 할 수 없습니다.

2. componentDidMount()

이 메서드는 Component가 DOM에 탑재된 후 호출됩니다. ComponentWillMount와 마찬가지로 생명주기에서 한 번 호출됩니다. 메서드가 실행되기 전 render 메서드는 호출됩니다.(i.e DOM에 접근할 수 있습니다.) API 호출 그리고 응답에 따른 state 수정도 할 수 있습니다.

DOM에 탑재되는 2가지 메서드를 코드로 보시죠

class LifeCycle extends React.Component {
  componentWillMount() {
      console.log('Component will mount!')
   }
  componentDidMount() {
      console.log('Component did mount!')
      this.getList();
   }
  getList=()=>{
   /*** method to make api call***/
  }
  render() {
      return (
         <div>
            <h3>Hello mounting methods!</h3>
         </div>
      );
   }
}

Updating

업데이트에서는 Component가 통과하는 세가지 단계가 있습니다. 만들어진 Component의 Mounting 단계가 끝난 후 Update 단계가 시작됩니다. 여기서는 Component의 state 값이 바뀌면서 re-rendering 됩니다.

이 단계는 Component의 데이터(state&props)가 클릭이나 타이핑 등등 유저 이벤트에 반응하여 수정됩니다. 그리고 Component의 re-rendering을 통하여 결과물을 가져옵니다. 이 단계에서 사용할 수 있는 메서드는 다음과 같습니다.

1. shouldComponentUpdate()

이 메서드는 Component가 업데이트 유무에 대해서 판단합니다. Default 값은 true입니다. 하지만 어떤 조건에서 Component를 다시 re-rendering 하려는 경우 shouldComponentUpdate 메서드는 올바른 곳입니다.

생각해보죠. 예를 들어 props 가 변경되었을 때만 Component의 re-rendering을 하고 싶을 때 이 메서드느 유용하게 사용될 것입니다. 이 메서드에서는 현재의 prop&state 값에 필적하여 re-rendering 유무를 결정할 수 있게 도와주는 nextProp과 nextState를 인자로 받습니다.

2. componentWillUpdate()

이 메서드는 Component가 re-rendering을 하기 전에 호출됩니다. shouldComponentUpdate 메서드가 호출된 후에 실행됩니다. Component가 re-rendering 하기전, state와 prop이 수정된 후에 어떤 계산을 수행하고 싶다면 알맞은 로직을 이곳에 작성하면 됩니다. ShouldComponentUpdate와 마찬가지로 nextProps와 nextState 인자를 받습니다.

3. componentDidUpdate()

이 메서드는 Component가 re-rendering을 한 후에 호출됩니다. 수정된 Component가 DOM에서 수정된 후 ComponentDidUpdate 메서드가 실행됩니다. 이 메서드는 prevProps와 prevState를 인자로 받습니다.

Updating 메서드를 정리해보면 다음과 같습니다.

class LifeCycle extends React.Component {
  constructor(props)
  {
    super(props);
     this.state = {
       date : new Date(),
       clickedStatus: false,
       list:[]
     };
  }
  componentWillMount() {
      console.log('Component will mount!')
   }
  componentDidMount() {
      console.log('Component did mount!')
      this.getList();
   }
  getList=()=>{
   /*** method to make api call***/
   fetch('https://api.mydomain.com')
      .then(response => response.json())
      .then(data => this.setState({ list:data }));
  }
   shouldComponentUpdate(nextProps, nextState){
     return this.state.list!==nextState.list
    }
   componentWillUpdate(nextProps, nextState) {
      console.log('Component will update!');
   }
   componentDidUpdate(prevProps, prevState) {
      console.log('Component did update!')
   }
  render() {
      return (
         <div>
            <h3>Hello Mounting Lifecycle Methods!</h3>
         </div>
      );
   }
}

Unmounting

Component 생명주기에 마지막 단계입니다. 이름에서 알수 있듯이 이 단계에서 Component는 DOM으로부터 탈착됩니다. 이 단계에 속해있는 메서드는 다음과 같습니다.

1. componentWillUnmount()

이 메서드는 Component가 탈착되기 전에 호출됩니다. DOM으로부터 Component의 제거가 이뤄지기 전 ComponentWillUnmount는 실행됩니다. 이 메서드는 Component 생명주기의 마지막을 장식합니다.

지금까지 알아본 생명주기를 정리해보면 다음과 같습니다.

profile
FrontEnd Developer

0개의 댓글