프로그래밍/React

React - 컴포넌트 Lift cycle

삐제제 2021. 8. 15. 18:00

 

 

 

 

 

 

 

class App extends React.Component {
  constructor(props) {
    super(props);
    console.log("constructor");
  }
  state = {
    count: 0,
  };
  add = () => {
    this.setState((currnet) => ({ count: currnet.count + 1 }));
  };
  minus = () => {
    this.setState((current) => ({ count: current.count - 1 }));
  };
  componentDidMount() {
    console.log("component rendered");
  }
  componentDidUpdate() {
    console.log("I just updated");
  }
  componentWillUnmount() {
    console.log("Goodbye, Cruel world");
  }
  render() {
    console.log("I'm rendering");
    return (
      <div>
        <h1>The number is : {this.state.count} </h1>
        <button onClick={this.add}>Add</button>
        <button onClick={this.minus}>Minus</button>
      </div>
    );
  }
}

export default App;

컴포넌트가 생성 될 때, render 전에 호출되는 몇가지 함수들도 있고, render 후에 호출되는 함수들도 있다.

 

아래 서술하는 것들은 존재하는 함수 전부가 아니라 자주 사용하는 함수 라고한다.

 

1. Mounting : 컴포넌트가 생성될 때! 

- constructor() : Javascript에서 class를 만들 때 호출되는 메서드 위 코드에서 가장 먼저 호출됨. (이건 리액트가 아니라 자바스크립트이다.)

- render(): constructor 이후에 실행됨.

- componentDidMount() : 컴포넌트 Mount가 완료되면 실행됨! (render 이후 실행!)

=> constructor -> render -> componentDidMount 순서

 

2. Update : 컴포넌트가 업데이트 될 때

 

- componentDidUpdate  : 업데이트가 완료되면 호출됨!

 

add를 두번 누르면 콘솔창은 다음과 같이 실행될 것이다.

 

* setState를 호출했기 때문에, render function이 호출됨. 그리고 업데이트가 완료 되면, componentDidUpdate() 호출 *

I'm rendering
Component rendered
// Update
I'm rendering
I just updated
I'm rendering
I just updated

 

3.Unmounting : 컴포넌트가 사라질 때

 

- componentWillUnmount 

'프로그래밍 > React' 카테고리의 다른 글

React - styled-components?  (0) 2021.08.19
React - CSS 모듈?  (0) 2021.08.19
React - 클래스 컴포넌트? state?  (0) 2021.08.12
React - PropTypes?  (0) 2021.08.10
React 공부 입성!  (0) 2021.08.10