본문 바로가기
Coding/React

React - State Life Cycle(state 생명주기)

by z쿳쿳z 2020. 7. 18.
728x90
반응형

State는 사람의 생명주기 처럼 생성(태어남) - 변화(성장) -제거(죽음)으로 구성 되어있다.

State가 생성될 때

  *constructor

  *render

순으로 저장이 되었다가 render가 끝나면 

  *componentDidMount

내장 메소드가 실행이 된다.

※Mount는 component가 처음으로 시작할 때를 말합니다.

 

업데이트할 때

  *render

순으로 React DOM 및 refs 업데이트가 되었다가 render가 끝나면

  *componentDidUpdate

내장 메소드가 실행이 된다.

 

제거할 때

  *componentWillUnmount

내장 메소드가 실행이 된다.

 

예시)

  예제 : https://programmingwithmosh.com/react/guide-to-learn-useeffect-hook-in-react/

  console을 확인 해보면 1이 2번 찍히고 componentDidMount가 되고, click을 누르면 componentDidupdate가 실행된다.

class App extends Component{
  state = {
    buttonPressed:''
  }

  componentDidMount(){
    console.log("Component did mount", this.state.buttonPressed)
  }

  componentDidUpdate(){
    console.log("Component did update", this.state.buttonPressed)
  }

  onYesPress() {
    this.setState({ buttonPressed: "Yes" });
  }

  onNoPress() {
    this.setState({ buttonPressed: "No" });
  }

  render () {
    return (
      <div className="App">
        <div>{console.log(1)}</div>
        <button onClick={() => this.onYesPress()}>Yes</button>
        <button onClick={() => this.onNoPress()}>No</button>
      </div>
    );
  }
}

 

 

LifeCycle

from codestates

 

componentDidMount

서버로 componentDidMount를 사용하는 이유는 render가 되기 전에 개인정보나 중요한 정보(password)같은 값들이 render가 되어서 화면에 표시 되는 것을 막을 수 있다.

componentDidMount(){
 //axios나 fetch를 이용해서 서버에서 data를 받아올 때 사용
}

 

shouldcomponetUpdate

props 또는 state가 변경되었을 때, 재랜더링을 여부를 Boolean으로 return 값으로 결정한다.

shouldcomponentUpdate(nextProp, nextState){
 //retunr true or false로 componentWillUpdate 실행여부 판단
}

 

componentDidUpdate

shouldcomponentUpdate에서 true값을 반환 했을 때, 실행되는 함수이다.

componentWillUpdate(nextProp, nextState){
 //새로운 props 또는 state가 반영되기 직전 새로운 값들을 받는다.
 //안에서 this.setState()를 사용하면 max callstack이 발생
}

 

componentWillUnmount

컴포넌트가 소멸되는 시점에 실행되어서 비동기 api를 제가한다.

componentWillUnmount() {
  // 이벤트, setTimeout, 외부 요소 제거
}

 

#React#codestates#lifecycle#componentDidMount#shouldcomponentUpdate#compopnentDidUpdate#componentWillUnmount

728x90
반응형

'Coding > React' 카테고리의 다른 글

React - Phone book 만들기(1)  (0) 2020.08.06
React - functional vs Class  (0) 2020.08.01
React - Lifting state(state 끌어올리기)  (0) 2020.07.13
React - props & state  (0) 2020.07.12