TIL. React- LifeCycle(생명주기)

hyemi jo·2021년 4월 26일
0
post-thumbnail

컴포넌트는 LifeCycle (생명주기)를 가진다.
생명주기란 컴포넌트가 생성되고 사용되고 소멸될 때 까지의 일련의 과정을 말한다.

LifeCycle 기본순서

  1. constructor
  2. render
  3. componentDidMount (ex: 데이터를 받는 fetch함수와 setState함수가 있을경우)
  4. (fetch 완료)
  5. render
  6. (setState)
  7. componentDidUpdate (setState가 되었기 때문에 업데이트 발생)
  8. componentWillUnmount

LifeCycle API

🔹constructor

constructor(props){
super();
this.state = { 
	data:[]
	}
}
  • 컴포넌트가 생성될 때 단 한번 만실행된다.
  • 초기 state를 정의 할 수 있다.

🔹render

  • 컴포넌트 렌더링을 담당한다.

🔹componentDidMount

componentDidMount(){
// 컴포넌트에서 필요한 데이터 요청
// 외부라이브러리 연동
// dom에 관련된 작업
};
  • 컴포넌트가 만들어지고 render 가 호출 된 이후에 호출된다.
  • 필요한 데이터를 axios, fetch 를 통해서 AJAX요청을 할 때, 외부 라이브러리를 연동할 때 , DOM에 관련된 작업(ex: 스크롤 설정)을 할 때 사용한다.

🔹componentDidUpdate

  • 컴포넌트가 setState로 업데이트 되고 리렌더링을 마친 후에 실행된다.

🔹componentWillUnmount

componentWillUnmount(){
    console.log("componentWillUnmount");
}
  • 컴포넌트가 DOM에서 사라진 후 실행된다.
  • 컴포넌트 제거




    📚Reference
  • LifeCycle
profile
기억보단 기록을📓

0개의 댓글