[React] Lifecycle 생명주기

Byunghoon Lee·2020년 10월 29일
5

React

목록 보기
3/4
post-thumbnail

Velopert - lifecycle

LifeCycle API 란?

컴포넌트가 브라우저에서 나타날때 , 사라질때 , 업데이트 될 때 호출되는 API 입니다.

v16.3 이전 구동순서

구동 순서는 아래와 같습니다.

🙅‍♂️ React 17 이후 부터는
componentWillMount, componentWillUpdate, componentWillReceiveProps 라이프 사이클이 deprecated 됩니다.

Mount

컴포넌트가 처음 실행되는것.

컴포넌트 초기 생성

컴포넌트가 브라우저에 나타나기 전 , 후에 호출되는 API는 아래와 같습니다.

constructor

constructor(props) {
  super(props);
}

이 부분은 컴포넌트 '생성자 함수' 입니다. 가장 먼저 실행되는 함수로 초기 state를 설정합니다.

🙅‍♂️ componentWillMount (알고만있자)

componentWillMount는 render가 되기 직전에 호출되는 API 로, 브라우저가 아닌 환경에서도 호출하는 용도로 사용했으나 , componentDidMount에서 처리할 수 있습니다. (있었다는것만 알아두자)

componentDidMount

componentDidMount() {
  // 외부 라이브러리 연동: D3, masonry, etc
  // 컴포넌트에서 필요한 데이터 요청: Ajax, GraphQL, etc
  // DOM 에 관련된 작업: 스크롤 설정, 크기 읽어오기 등
}

componentDidMount는 컴포넌트가 화면에 나타나게 됐을 때 호출 되며 , 즉 render 후에 호출이 됩니다.
보통 컴포넌트에서 fetch,axios등을 통해 데이터를 받아오는데 사용 합니다.

컴포넌트 업데이트

🙅‍♂️ componentWillReceiveProps(nextProps)

componentWillReceiveProps(nextProps){
  console.log("componentWillReceiveProps: " + JSON.stringify(nextProps));
}

컴포넌트 생성후 첫 렌더링을 마친 후 호출 되는 함수입니다.
props를 받아서 state를 변경해야 하는 경우 유용 합니다.
setState를 사용해도 추가적인 렌더링이 발생하지 않습니다.

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate(nextProps, nextState){
  console.log("shouldComponentUpdate: " + JSON.stringify(nextProps) + " " + JSON.stringify(nextState));
  return true;
}

컴포넌트 업데이트 직전에 호출되는 메소드 입니다.
propsstate가 변경 되었을 때 리렌더링 여부를 return 값으로 정합니다.

🙅‍♂️ componentWillUpdate(nextProps, nextState)

componentWillUpdate(nextProps, nextState){
  console.log("componentWillUpdate: " + JSON.stringify(nextProps) + " " + JSON.stringify(nextState));
}

shouldComponentUpdate가 불린 이후 컴포넌트 업데이트 직전에 호출되는 함수 입니다.
이 함수 안에서 setState()를 사용하면 무한루프가 일어나게 되므로 사용하지 말자.

componentDidUpdate(prevProps, prevState)

componentDidUpdate(prevProps, prevState){
  console.log("componentDidUpdate: " + JSON.stringify(prevProps) + " " + JSON.stringify(prevState));
}

컴포넌트 업데이트 직후에 호출 되는 함수입니다.

componentWillUnmount()

componentWillUnmount(){
  console.log("componentWillUnmount");
}

컴포넌트가 DOM에서 삭제된 후 실행되는 함수입니다.

v16.3 이후 변경부분

  • componentWillMount, componentWillReceiveProps, componentWillUpdate를 v17 부터 사용불가
  • componentWillReceiveProps => getDerivedStateFromProps
  • componentWillUpdate => getSnapshotBeforeUpdate
  • componentDidCatch 컴포넌트 에러 핸들링 API추가
  • v16.3 이전에는 렌더링을 제어하는 방법이 많아져 혼란스러웠음.
  • React 커뮤니티에서도 가장 혼란을 야기 함.

v16.3 이후 구동 순서

static getDerivedStateFromProps(nextProps, prevState)

getDerivedStateFromPropscomponentWillReceiveProps의 대체 역할로 ,
props로 받아온 것을 state에 넣어주고 싶을때 사용합니다.
여기선 state값을 변경하고 싶으면setState를 사용하는 것이 아닌 return을 사용 해야 합니다. null을 반환하게 되면 아무 일도 발생하지 않습니다.

이 함수는 컴포넌트가 처음 렌더링 되거 전에도 호출 되고 , 리렌더링 되기 전에도 매번 호출 됩니다.

  • componentWillReceiveProps(nextProps) (v16.3 이전)
componentWillReceiveProps(nextProps) {
  if (this.props.name !== nextProps.name) {
    this.setState({ name: nextProps.name });
  }
}
  • static getDerivedStateFromProps(nextProps, prevState) (v16.3 이후)
static getDerivedStateFromProps(nextProps, prevState) {
  if (prevState.name !== nextProps.name) {
    return { name: nextProps.name };
  }

  return null;
}
profile
Never never never give up!

0개의 댓글