본문 바로가기
JavaScript/React

[React] #3.2 Component Life Cycle (#코딩공부)

by 함께 공부해요 2020. 5. 27.

https://youtu.be/ycOQk7SZWkM


<복습>

https://wook-2124.tistory.com/133

 

[React] #3.1 All you need to know about State (#코딩공부)

https://youtu.be/38I5K3p42WU <복습> https://wook-2124.tistory.com/132 [React] #3.0 Class Components and State (#코딩공부) https://youtu.be/rEazMgq2D8M <복습> https://wook-2124.tistory.com/131 [React..

wook-2124.tistory.com

 

<준비물>

https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

ko.reactjs.org/docs/react-component.html

 

React.Component – React

A JavaScript library for building user interfaces

ko.reactjs.org


1. React Component Life Cycle

React Component Life Cycle은 기본적으로 React에서 component를 생성하고 없애는 cycle이다.


2. Mounting(마운트)

Mount는 component를 create(생성)하는 행위이다. 여기서 constructor, render, componentDidMount가 있는데 이것들 중 어떤것이 먼저 실행될지 살펴보자.

 

component가 mounting(생성)될 때, 즉 screen에 표시되거나 Website로 갈 때 constructor와 render 중 어떤 것이 먼저 실행되는지 console.log로 확인해보면 constructor가 render보다 먼저 호출되는 것을 알 수 있다.

 

constructor는 JavaScript에서 class를 만들 때 호출되는 것이기 때문에 React component가 실행되기 전에 실행되고, render는 React가 실행됨에 따라 React의 method로써 실행된다.

 

그렇다면 순서대로 componentDidMount는 constructor가 JavaScript에 의해 class를 만들 때 실행되고, React method로써 render가 실행된 다음 component가 이제 Mount(생성)됐다는 것, 화면에 render(표현)됐다는 것을 알려주는 역할이다.

 

살펴보자면, ①constructor가 실행되고 ②render가 실행된 후 React가 render를 return(반환)하면, ③componentDidMount가 실행되서 Mount가 성공적으로 마쳤다는 것을 알려준다.

 

하지만 constructor는 React가 아니라 JavaScript이기 때문에 사용할 필요가 없다. 


3. Updating(업데이트)

Updating은 setState를 호출해서 state가 변경될 때 마다 발생하는 것이다. componentDidUpdate 역시 순서에 맞게 React가 render를 return(반환)한 다음에 호출되는 것이다.

 

console.log로 componentDidUpdate가 언제 생기는지 확인해보면,

 

위에서 보이는 것처럼 사이트에 제대로 Mounting(생성)이 완료되서 render function과 componentDidMount에 적은 내용이 나오는 것을 알 수 있다. 그리고 기본적으로 Updating도 Mounting처럼 render function이 먼저 실행된 다음에 componentDidUpdate를 실행한다.

 

setState를 호출하면 state(상태)의 변경으로 인해 render를 다시 호출하게 된다. 그리고 Updating이 완료됐다고 알려주는 componentDidUpdate가 실행된다.

 

여기서 중요한 것은 setState로 state(상태)에 변화를 줄 때마다, render 역시 다시 호출된다는 것이다.


4. Unmounting(마운트 해제)

componentWillUnmount다른 page로 넘어가는 것처럼 Mounting된 component로부터 떠날 때, 혹은 component가 삭제거나 교체될 때 호출된다.

 

ko.reactjs.org/docs/react-component.html

 

React.Component – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

댓글