React기본) Component Lifecycle (< v16.3)

lbr·2022년 8월 9일
0

Component Lifecycle (< v16.3)

  • Initialization : 처음에 constructor가 불리면서 props가 셋팅되고 state의 초기값이 설정되는 구간입니다.

  • render : 브라우저에 최초로 그려지는 부분입니다.

  • componentWillUnmount : 컴포넌트가 사라지면 해당 컴포넌트는 이미 인스턴스가 아니기 때문에 사라진 후의 작업은 할 수 없습니다. 그래서 사라지기 직전을 의미하는 componentWillUnmount 에 대한 설정만 가능합니다.

  • Updation에서 propsstates가 변경될 때는 결정적으로 하나의 차이가 있습니다.
    props일 경우에만 componentWillReceiveProps 라는 훅이 앞에 하나 더 있습니다. 그 이후에는 완전히 같습니다.

  • shouldComponentUpdate 이름이 말해 주듯이 컴포넌트가 업데이트 되어야 하는지 안되어야 하는지에 대한 결정을 할 수 있는 구간입니다.
    이 부분이 상당히 중요합니다. 이 부분의 true 또는 false 의 리턴을 가지고 그 이후에 실제로 render가 되지 않게 조절을 할 수도 있습니다. 불필요하게 render 될 경우 방지 할때 도움이 됩니다. 그래서 react 컴포넌트의 성능 최적화에 아주 중요한 역할을 하는 lifecycle hook입니다.

이전 버전의 lifecycle hook을 배우는 이유는 현재 최신으로 바뀐 lifecycle hook에 대한 이해에 훨씬 더 도움이 되기 때문입니다.

Component 생성 및 마운트 (< v16.3)

생성 : 객체화되는 구간
마운트 : 그리는 구간 (render)

  • constructor
  • componentWillMount
  • render (최초 랜더)
  • componentDidMount

각각의 hook 이 동작하는 순서 확인해보기

class App extends React.Component {
  state = {
    age: 39
  };
  constructor(props) {
    super(props);

    console.log("constructor", props);
  }

  render() {
    // 최초 render (=mount)
    console.log("render");
    return (
      <div>
        <h2>
          Hello {this.props.name} - {this.state.age}
        </h2>
      </div>
    );
  }
  componentWillMount() {
    console.log("componentWillMount");
  } // 우리는 여기에 정의만 해놓으면 react가 알아서 부를것입니다.
  componentDidMount() {
    // 최초 render가 된 다음에 보통 여기서 여러가지 처리를 해줍니다.
    // 타이머, api 요청 등등..
    console.log("componentDidMount");

    setInterval(() => {
      console.log("setInterval");
      this.setState(state => ({...state, age: state.age + 1}));
    }, 1000);
  } // 우리는 여기에 정의만 해놓으면 react가 알아서 부를것입니다.
}

결과

중간의 Warning 은 componentWillMount 가 이전 버전 이라고 알려주고 있습니다.

componentDidMount() 에 기능 넣어보기

componentDidMount() {
  // 최초 render가 된 다음에 보통 여기서 여러가지 처리를 해줍니다.
  // 타이머, api 요청 등등..
  console.log("componentDidMount");

  setInterval(() => {
    console.log("setInterval");
    this.setState(state => ({...state, age: state.age + 1}));
  }, 1000);
} // 우리는 여기에 정의만 해놓으면 react가 알아서 부를것입니다.

결과

setState()로 인해 state 값이 바뀌면서 render도 같이 실행되고 있습니다.

Component props, state 변경 (< v16.3)

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate
componentWillReceiveProps(nextProps) {
  //nextProps : 바뀔 Props
  console.log("componentWillReceiveProps", nextProps);
}

shouldComponentUpdate(nextProps, nextState) {
  console.log("shouldComponentUpdate", nextProps, nextState);

  //return false; // 여기서 false를 return한다면 render가 일어나지 않고 그 이후 hook들도 동작 하지 않습니다.
  return true;
}

componentWillUpdate(nextProps, nextState) {
  console.log("componentWillUpdate", nextProps, nextState);
}

componentDidUpdate(prevProps, prevState) {
  // render가 된 후에 불려지므로 인자 이름을 prev로 했습니다.
  console.log("componentDidUpdate", prevProps, prevState);
}

componentWillReceiveProps

  • props 를 새로 지정했을 때 바로 호출됩니다.
  • 여기는 state 의 변경에 반응하지 않습니다.
    - 여기서 props 의 값에 따라 state 를 변경해야 한다면,
    - setState 를 이용해 state 를 변경합니다.
    - 그러면 다음 이벤트로 각각 가는것이 아니라 한번에 변경됩니다.
    - 모아서 shouldComponentUpdate(nextProps, nextState) 에 한번에 갑니다.

shouldComponentUpdate

  • props 만 변경되어도 실행되고,
  • state 만 변경되어도 실행되고,
  • props & state 둘다 변경되어도 실행됩니다.
  • newProps 와 new State 를 인자로 해서 호출
  • return type 이 boolean 입니다.
    - true 면 render
    - false 면 render 가 호출되지 않습니다.
    - 이 함수를 구현하지 않으면, 디폴트는 true

componentWillUpdate

  • 컴포넌트가 재 랜더링 되기 직전에 불립니다.
  • 여기선 setState 같은 것을 쓰면 안됩니다.

componentDidUpdate

  • 컴포넌트가 재 랜더링을 마치면(랜더가 된 직후) 불립니다.

Component 언마운트 (< v16.3)

componentWillUnmpunt

  • 컴포넌트가 사용했던 메모리 중에 정리할 것이 있다면 정리하거나
  • api 요청을 component에서 보냈는데 이 컴포넌트가 api 응답을 받기 전에 unmount 된다면, 그 api를 더 이상 받을 준비를 하지 않겠다. 라는 처리를 여기서 해주어야 합니다.

예시

componentWillUnmpunt() {
  clearInterval(this.intervalId);
}

0개의 댓글