React 라이프사이클 (LifeCycle)

Southbig·2022년 8월 17일
0

컴포넌트 라이프사이클은 컴포넌트의 생성부터 소멸에 이르는 일련의 이벤트로,
모든 리액트 컴포넌트에는 LifeCycle을 갖는다

class component

컴포넌트 라이프사이클 메서드

1. Mounting

컴포넌트의 인스턴스가 생성되 DOM상에 삽입되는 단계다
Mounting은 LifeCycle이 종료될 떄까지 한 번만 일어난다
아래 메서드들은 이 단계에서 순서대로 호출 된다

  • constructor : 컴포넌트의 인스턴스를 새로 만들때마다 생성자 메서드 호출
  • render: 화면에 표현될 JSX를 반환하고 화면에 그림
  • componentDidMount: 컴포넌트가 화면에 모두 그려진 이후 호출됨

componentDidMount 메서드는 첫 렌더링 이후 실행된다
앤드포인트에서 클라이언트로 데이터를 불러와야 하는 경우 API 호출을 하기 좋은 위치다
데이터를 받아 올 때 setState 메서드를 이용해 컴포넌트를 업데이트 할 수 있다

2. Updating

props또는 state가 변경되 컴포넌트가 업데이트되는 단계다
아래 메서드들이 이 단계에서 순서대로 호출된다

  • static getDerivedStateFromProps
  • shouldComponentUpdate
  • render: 데이터가 변경되면 자동으로 호출됩니다. 화면에 다시 그림
  • getSnapshotBeforeUpdate
  • componentDidUpdate: 화면이 다시 그려진 후 호출

3. Unmounting

컴포넌트가 DOM 상에서 제거되는 단계

  • componentWillUnmount: 컴포넌트가 화면에서 제거되기전 호출된다

LifeCycle메서드 실행 과정

1. Mounting

부모컴포넌트 constructor, render 호출 -> 자식 컴포넌트 constructor, render 호출

Mounting 단계는 부모컴포넌트 render가 호출된 다음 자식 컴포넌트의 Mounting 단계가 실행된다
만약에 부모컴포넌트와 자식컴포넌트가 모두 componentDidMount 메서드를 호출한다면 자식컴포넌트에서 먼저 호출 된다

2. Updating

마운트 단계에서 componentDidMount메서드 호출시 setState를 통한 컴포넌트 업데이트 시

부모 컴포넌트 constructor, render 호출 -> 자식 컴포넌트 constructor, render 호출 -> 자식 컴포넌트 conponentDidMount 호출 -> 부모 컴포넌트 conponentDidMount 호출 -> 부모컴포넌트 render 호출 -> 자식 컴포넌트 render 호출 -> 자식 컴포넌트 conponentDidUpdate 호출 -> 부모 컴포넌트 conponentDidUpdate 호출 ->

3. Unmounting

언마운팅은 컴포넌트 돔에서(화면에서) 제거되는 것이다

componentDidMount메서드를 이용해 자식컴포넌트를 화면에서 제거한다면

부모 컴포넌트 constructor, render 호출 -> 자식 컴포넌트 constructor, render 호출 -> 자손 컴포넌트 constructor, render 호출 -> 자손 conponentDidMount 호출 -> 자식 컴포넌트 conponentDidMount 호출 -> 부모 컴포넌트 conponentDidMount 호출 -> 부모컴포넌트 render 호출 -> 자식 컴포넌트 render 호출 -> 자손 컴포넌트 render 호출 -> 자손 컴포넌트 conponentDidUpdate 호출 -> 자식 컴포넌트 conponentDidUpdate 호출 -> 부모 컴포넌트 conponentDidUpdate 호출 ->

라이프 사이클 메서드 호출순서

최초 : constructor -> getDerivedStateFromProps -> componentDidMount
업데이트 : getDerivedStateFromProps -> componentDidUpdate
언마운트 : componentWillUnmount

함수 컴포넌트

Hook에서는 useEffet()가 위 생명주기 함수들을 대체

profile
즐겁게 살자

0개의 댓글