컴포넌트는 LifeCycle (생명주기)를 가진다.
생명주기란 컴포넌트가 생성되고 사용되고 소멸될 때 까지의 일련의 과정을 말한다.
LifeCycle 기본순서
- constructor
- render
- componentDidMount (ex: 데이터를 받는 fetch함수와 setState함수가 있을경우)
- (fetch 완료)
- render
- (setState)
- componentDidUpdate (setState가 되었기 때문에 업데이트 발생)
- componentWillUnmount
LifeCycle API
🔹constructor
constructor(props){
super();
this.state = {
data:[]
}
}
- 컴포넌트가 생성될 때 단 한번 만실행된다.
- 초기 state를 정의 할 수 있다.
🔹render
🔹componentDidMount
componentDidMount(){
};
- 컴포넌트가 만들어지고
render
가 호출 된 이후에 호출된다.
- 필요한 데이터를 axios, fetch 를 통해서 AJAX요청을 할 때, 외부 라이브러리를 연동할 때 , DOM에 관련된 작업(ex: 스크롤 설정)을 할 때 사용한다.
🔹componentDidUpdate
- 컴포넌트가 setState로 업데이트 되고 리렌더링을 마친 후에 실행된다.
🔹componentWillUnmount
componentWillUnmount(){
console.log("componentWillUnmount");
}
- 컴포넌트가 DOM에서 사라진 후 실행된다.
- 컴포넌트 제거
📚Reference
- LifeCycle