React Life Cycle

김승ㅈIT·2023년 2월 10일

Mount

컴포넌트가 처음 실행될 때 그것을 Mount라고 표현한다.

  1. 컴포넌트가 시작되면 우선 context, defaultProps와 state를 저장한다.
  2. componentWillMount호출 Mount중이기 때문에 props나 state를 바꾸면 안된다. 아직 DOM에 render하지 않았기 때문에 DOM에 접근할 수 없다.
  3. render로 컴포넌트를 DOM에 부착하고 Mount가 완료된 후 componentDidMount가 호출 된다. 이제 DOM에 접근할 수 있다. 주로 AJAX요청 및 setTimeout, setInterval 같은 행동을 한다.

🔥 Mount 순서정리 🔥
1. state, context, defaultProps 저장
2. componentWillMount
3. render (컴포넌트를 렌더링하는 메서드)
4. componentDidMount


Updating

Props Updating

props가 업데이트될 때의 과정

업데이트되기 전 업데이트가 발생하였음을 감지하고 componentWillReceiveProps ⇒ shouldComponentUpdatecomponentWillUpdate 메소드 차례대로 호출된 후,
업데이트가 완료(render)되면 componentDidUpdate 된다.
위 메소드들은 첫 번째인자로 바뀔 props에 대한 정보를 가지고 있다.
componentDidUpdate만 이미 업데이트되었기 때문에 바뀌기 이전의 props에 대한 정보를 가지고 있다.

shouldComponentUpdate
아직 render하기 전이기 때문에 reder를 취소할 수 있다.
주로 여기서 불필요한 update에 대한 성능 최적화를 한다.

componentWillUpdate
state를 바꿔서는 안 된다. 아직 props도 업데이트하지 않았으므로 state를 바꾸면 또 shouldComponentUpdate가 발생합니다.

componentDidUpdate
render이 완료되었기 때문에 DOM에 접근할 수 있습니다.

🔥 Props Update 순서 정리 🔥
1. componentWillReceiveProps
2. shouldComponentUpdate
3. componentWillUpdate
4. render
5. componentDidUpdate

State Updating

setState 호출을 통해 state가 업데이트될 때의 과정

props update와 과정이 같지만, componentWillReceiveProps 메소드는 호출되지 않는다. 그리고 메소드의 두 번째 인자로는 바뀔 state에 대한 정보를 가지고 있습니다.
componentDidUpdate는 두 번째 인자로 바뀌기 이전의 state에 대한 정보를 가지고 있습니다.

🔥 State Update 순서 정리 🔥
1. shouldComponentUpdate
2. componentWillUpdate
3. render
4. componentDidUpdate


Unmount

컴포넌트가 제거되는 것은 Unmount라고 표현한다.

componentWillUnmount
더는 컴포넌트를 사용하지 않을 때 발생하는 이벤트
이미 제거된 컴포넌트에서 이벤트를 발생시킬 수 없기 때문에 componentDidUnmount는 존재하지 않는다.

참고 자료
https://www.zerocho.com/category/React/post/579b5ec26958781500ed9955

0개의 댓글