by brgfx - kr.freepik.com

Lifecycle?

In general, we might define a lifecycle as birth, growth & death. And our React components follow this cycle as well: they’re created (mounted on the DOM), they experience growth (by updating) and they die (unmounted from the DOM). This is the component lifecycle!
by Timothy Robards https://itnext.io/react-understanding-state-lifecycle-d45df5d2cf3f

React에서 컴포넌트도 인간의 삶과 비슷하게 Lifecycle을 가진다 DOM에 마운트되어 태어나고 Updating을 통해 성장하며 최종적으로는 DOM에서 언마운트되어 죽음을 맞이한다. 이것이 State Lifecycle이다.

이러한 Lifecycle동안 각각의 Phase는 각 단계 method들을 가진다.

1. Initialization

Initialization 단계에서는 state와 props를 설정한다.

2. Mounting

그 다음은 리액트 컴포넌트가 DOM에 마운트 되는 단계이다. 여기서 사용할 수 있는 Method로는 componentWillMount()componentDidMount()가 있다.

componentWillMount()

컴포넌트가 DOM에 마운트되기 직전에 호출된다.

componentDidMount()

컴포넌트가 DOM에 마운트되고 난 후에 호출된다. 이 메소드는 render메소드가 실행되고 나서 실행된다.
componentWillMount와 마찬가지로 이 메소드는 lifecycle동안에 단 한번만 호출된다.

3. Updating

마운팅 페이즈가 끝나면 업데이트 페이즈로 들어간다. 이 단계에서 컴포넌트의 state가 변화된다면 리렌더링이 일어난다. 이때 사용되는 Method로는 shouldComponentUpdate()componentWillUpdate() , componentDidUpdate()가 있다.

shouldComponentUpdate()

이 메소드는 컴포넌트가 업데이트 되어야하는지 말아야하는지를 결정한다. default로는 true를 리턴한다. 만약 조건에 따른 렌더링을 하고싶다면 이 메소드를 쓰면된다.

여기서 리렌더링 할지말지 결정하기위해 사용될 nextProps 와 nextState를 인자로 받는다

componentWillUpdate()

이 메소드는 컴포넌트를 리렌더 하기전에 호출된다. shouldComponentUpdate()메소드가 호출되고 난후에 호출된다.

shouldComponentUpdate()와 마찬가지로 nextProps 와 nextState를 인자로 받는다.

componentDidUpdate()

리렌더링이 되고난후에 이 메소드가 호출된다. prevProps 와 prevState를 인자로 받는다.

4. Unmounting

마지막 페이즈는 컴포넌트가 DOM에서 unmount되는 마운팅 페이즈이다.

componentWillUnmount()

언마운팅이 일어나기 전에 이 메소드가 호출된다. 컴포넌트가 죽기직전! 마지막으로 호출되는 메소드이다.


글에서 알아본 lifecycle메소드는 클래스형 컴포넌트에서만 사용할 수 잇다. 또한componentWillMount()componentWillUpdate() 메소드는 버전업이 되면서 deprecate된 메소드이다.

클래스형 컴포넌트를 더이상 사용하지 않고 함수형 컴포넌트에서 lifecycle method가 필요할경우 useEffect와 같은 hook을 사용하면된다.

profile
FE 개발 velog

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN