본문 바로가기

프로그래밍/React

[React 요약 정리] 4. React 컴포넌트 라이프사이클 이벤트

4. React 컴포넌트 라이프사이클 이벤트

1) 개요

- React는 라이프사이클 이벤트를 기반으로 컴포넌트 동작 제어, 사용자 정의 가능

- 모든 React 컴포넌트는 라이프사이클 이벤트가 존재

- 종류

마운팅 이벤트: React 엘리먼트를 DOM 노드에 추가 시 발생

갱신 이벤트: React 엘리먼트 갱신 시 발생

언마운팅 이벤트: React 엘리먼트를 DOM에서 제거 시 발생


2) 이벤트 종류

- 마운팅

componentWillMount(): DOM 삽입 전 실행 // 라이프 사이클 중 1회만 실행

componentDidMount():  DOM 렌더링 완료 후 실행 // Fetch API의 XHR요청 작성 가능


- 갱신

componentWillReceiveProps(nextProps): 컴포넌트가 속성을 전달받기 직전에 실행

shouldComponentUpdate(nextProps, nextState): 렌더링 직전에 실행

*false반환시 재렌더링을 막을 수 있어서 최적화에 사용 가능

componentWillUpdate(nextProps, nextState): 새로운 속성, 상태를 받고 렌더링 직전에 실행

componentDidUpdate(nextProps, nextState): 컴포넌트 갱신 반영 후 실행


- 언마운팅

componentWillUnmount(): 컴포넌트를 DOM에서 제거하기 전에 실행

*이벤트 제거 및 정리 작업 수행 가능


- 수동으로 갱신해야하는 경우 this.forceUpdate() 메소드를 사용해야 하는데 순수성을 해친다는 이유로 권장되지 않음

*순수 함수: 같은 입력에 대해 항상 같은 출력, 외부 상태를 변경하거나 의존하지 않음


3) 이벤트 구현

- 클래스에 메소드를 정의함으로서 라이프사이클 이벤트를 구현 가능

- 예시

class Logger extends React.Component {

 constructor(props) {

   super(props)

   console.log('constructor')

 }

 componentWillMount() {

   console.log('componentWillMount is triggered')

 }

 componentDidMount(e) {

   console.log('componentDidMount is triggered')

   console.log('DOM node: ', ReactDOM.findDOMNode(this))

 }

 componentWillReceiveProps(newProps) {

   console.log('componentWillReceiveProps is triggered')

   console.log('new props: ', newProps)

 }

 shouldComponentUpdate(newProps, newState) {

   console.log('shouldComponentUpdate is triggered')

   console.log('new props: ', newProps)

   console.log('new state: ', newState)

   return true

 }

 componentWillUpdate(newProps, newState) {

   console.log('componentWillUpdate is triggered')

   console.log('new props: ', newProps)

   console.log('new state: ', newState)

 }

 componentDidUpdate(oldProps, oldState) {

   console.log('componentDidUpdate is triggered')

   console.log('new props: ', oldProps)

   console.log('old props: ', oldState)

 }

 componentWillUnmount() {

   console.log('componentWillUnmount')

 }

 render() {

   // console.log('rendering... Display')

   return (

     <div>{this.props.time}</div>

   )

 }

}



'프로그래밍 > React' 카테고리의 다른 글

[React 요약 정리] 3. JSX  (0) 2019.02.10
[React 요약 정리] 2. React 기초  (0) 2019.02.10
[React 요약 정리] 1. React 개요  (0) 2019.02.10