본문 바로가기

React

React의 Life Cycle




오늘은 React의 Life Cycle(생명주기)에 대해서 알아 보도록 하겠습니다. React에는 Component가 생성 되고 소멸 될 동안 단계별로 Component를 컨트롤 할 수 있도록 여러 메소드들이 있는데 우리는 그 메소드들을 오버라이드 해서 사용 할 수 있습니다.


The Component Lifecycle


Component 의 Lifecycle 은 크게 이렇게 나누어 살펴 볼 수 있습니다.


Mounting

Component의 인스턴스가 생성되고 DOM의 삽입 될때 과정입니다. 이 순서대로 진행 됩니다.
  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()


* 참고


원래는 static getDerivedStateFromProps() 대신 componentWillMount() 가 들어갔지만 지금은 레거시로 간주 되어 사용하지 않는 것을 권장하고 있습니다. 



Update


Props 나 State가 변화가 일어났을때 과정입니다. 이 순서대로 진행 됩니다.


  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • getSnapshotBeforeUpdate()
  • componentDidUpdate()

* 참고


아래에 있는 메소드 역시 레거시로 간주 하는 메소드들입니다.

  • componentWillUpdate()
  • componentWillReceiveProps()



Unmounting


Component가 DOM에서 제거 될 때 호출 되는 메소드입니다.


  • componentWillUnmount()


Error Handling


Life cycle 메소드나 하위 컴포넌트의 생성자에서 오류가 발생하면 호출 되는 메소드입니다.


  • componentDidCatch()

그럼 이제 주요 메소드를 하나씩 알아 보도록 하겠습니다.

Commonly Used Lifecycle Methods


컴포넌트가 생성 되고 사용 될 가능성이 높고 Component의 Lifecycle에 많은 부분을 차지하는 메소드들입니다.

render()
render() 메소드는 Class Component의 필수적으로 들어가야 하는 메소드입니다.

  • React elements 일반적으로 JSX를 통해 생성됩니다.
return (
<div className="wrap-movie">
<div className="movie-poster">
<MoviePoster poster={posterUrl}/>
</div>
<div className="box-movie">
<span className="movie-title">{title}</span>
<div className="movie-genres">
{genres.map((genre, idx) => {<MovieGenre genres={genre} index={idx}/>})}
</div>
<p className="movie-synopsis">
{synopsis}
</p>
</div>
</div>
)
  • Array and Fragments Fragments를 사용하면 자식 컴포넌트들을 그룹화 할 수 있다. Fragments 를 자세히 알아 보실 수 있습니다.
  • Portals Portals 는 부모 Component의 DOM계층 외부에 존재하는 DOM 노드 자식에 렌더링하는 일급 방법을 제공한다. 자세히 알아 보고 싶다면 Portals 링크를 참조 하세요.
 ReactDOM.createPortal(child, container)
  • String and numbers 이들은 텍스트 노드로 DOM에 렌더링 됩니다.
  • Booleans or null 렌더링되면 안됩니다. 이 둘은 어떠한 판단이나 테스트를 위해 존재하며, 렌더링 될 요소는 아닙니다.
추가적으로 render() 는 순수한 함수입니다. 즉, 입력이 동일하면 출력 또한 항상 동일 하여야 합니다.

* 참고

render() 는 shouldComponentUpdate()  가 false를 반환 하면 호출 되지 않고 True면 자동 호출 됩니다.



constructor()


State를 초기화 하지 않고 메소드를 바인딩 하지 않는 다면 constructor()를 쓸 필요 없습니다.


Component가 마운트 되기전에 constructor()가 먼저 호출 되며 구현 시에는 super()가 다른 구문들 맨 앞에 오게 해야 합니다.

그 이유는 그렇지 않으면 this.props 가 정의 되지 않아 오류가 발생 할 수 있습니다. 


일반적으로 React의 constructor는 두 가지 용도로만 사용됩니다.


  • this.state Oject를 통해 local state (Component) 를 초기화 합니다.
  • 이벤트 처리기 메소드를 바인딩 합니다.

constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}


주의 사항은 state 는 this.state를 통해 초기화만 이루어져야 합니다. this.setState() 를 통한 state의 업데이트가 이루어지면 안됩니다.


componentDidMount()

Component가 마운트 된 후 즉시 호출 됩니다. 그러므로 DOM 노드에서 필요한 초기화는 이 메소드에서 진행 되어야 합니다.


class App extends Component {
state = {};


/**
* Life cycle of React
*/
componentDidMount() {
this._getMovies();
}
}



componentDidUpdate()


State가 업데이트 발생 한 직후 호출 됩니다. 초기 렌더링에서는 호출 되지 않습니다. 


componentDidUpdate(prevProps, prevState, snapshot)



componentDidUpdate(prevProps) {
// Typical usage (don't forget to compare props):
if (this.props.userID !== prevProps.userID) {
this.fetchData(this.props.userID);
}
}
}


위 예제처럼 조건을 걸어 두지 않으면 무한 루프에 빠질 수 있습니다. 또는 조건을 제대로 정확하게 걸어 두지 않으면 불필요한 추가 렌더링이 발생 할 수 있습니다. 물론 유저들에게는 잘 보이지 않겠지만 이건 성능상 매우 치명적일 수 있습니다.


* 참고


componentDidUpdate()는 shouldComponentUpdate()가 false를 반환하면 호출 되지 않습니다.



componentWillUnmount()


마운트가 해제되거나 소멸 되기 직전에 호출 됩니다.


componentWillUnmount()


마운트가 된 컴포넌트에 마운트가 해제 되면서 제거 되거나 정리 되어야 하는 요소들은 이 메소드에 작성 하여 주시면 됩니다.



이상으로 포스팅을 마치겠습니다. 읽어 주셔서 감사하고 잘못 된 부분이 있다면 고수분들께서는 언제나 지적 부탁 드립니다.





[Reference] - https://reactjs.org/docs/react-component.html

'React' 카테고리의 다른 글

Props 와 State  (0) 2018.07.13
React 란 무엇 일까?  (0) 2018.07.13