react 생명 주기

Doum Kim·2020년 5월 15일
0

React - 기초

목록 보기
19/20
post-thumbnail

React 컴포넌트는 생명 주기가 있다. 컴포넌트가 실행, 업데이트, 제거될 때 특정한 이벤트들이 발생한다.

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

Mount(생성될 때)

컴포넌트가 처음 생성 될 때를 mount라고 한다. mount가 되면 state, defaultProps, context를 저장한다.
그리고 componentWillMount 메소드가 호출되고 render 메소드로 컴포넌트를 DOM, ref 업데이트를 해준다.
mount가 끝나면 componentDidMount 메소드가 호출된다.

componentWillMount에서는 props 또는 state을 변경해서는 안 된다. DOM에도 접근할 수 없다.

componentDidMount에서는 DOM에 접근이 가능하다. 여기서 비동기통신, setInterval, setTimeout을 다룬다.

state, defaultProps, context를 저장 → componentWillMount → render → componentDidMount

Update(업데이트할 때)

props 업데이트

props가 업데이트 될 때의 과정은 업데이트 발생을 감지하면 componentWillReceiveProps 메소드가 호출된다.
그 후에 shouldComponentUpdate, componentWillUpdate가 차례대로 호출되고 render 후에 componentDidUpdate가 된다. 앞의 메소드들은 첫 번째 인자로 바뀔 props의 값을 가지고 있다.
하지만 componentDidUpdate는 업데이트가 이미 된 상태이기 때문에 이전의 props 값을 가지고 있다.

render하기 전 상태인 sholudcomponentUpdate에서는 return false를 하면 render를 취소할 수 있다.
이걸 이용해서 성능 최적화를 할 수 있다. 불필요한 업데이트를 방지한다.

componentWillUpdate에서는 state 변경을 해서는 안된다. props도 업데이트하지 않았기 때문에 state를 바꾸면 shouldComponentUpdate가 또 발생을 한다.

componentDidUpdate에서는 render가 완료되어 DOM에 접근 가능하다.

state 업데이트

props 업데이트 과정과 비슷하다. 메소드의 두 번재 인자로 바뀔 state에 대한 값을 가지고 있다.
componentDidUpdate에서는 props와 마찬가지로 바뀌기 전의 state에 대한 값을 가지고 있다.

Unmount (제거할 때)

더이상 컴포넌트를 사용하지 않을 때 componentWillUnmount가 발생한다. 여기서 주로 DOM에 직접 등록했던 이벤트를 제거하고 외부 라이브러리를 dispose 해주거나 setTimeout, setInterval 등을 clear 해주면 된다.

0개의 댓글