리액트 복습 - 라이프 사이클

Jaemin Jung·2021년 8월 5일
0

React

목록 보기
3/10
post-thumbnail

Life Cycle

리액트 클래스 컴포넌트는 단순히 render 함수 말고 더 많은 것을 가지고 있다.

우선 컴포넌트가 생성 될 때, render 함수가 실행되기 전, 호출되는 몇 가지 function이 있다.

반대로 컴포넌트가 render 된 후, 호출되는 다른 function들이 존재한다.

그리고 컴포넌트가 update 된 후, 호출되는 function도 존재한다.

이 들을 life cycle method라고 부른다.

Mounting

Mounting을 쉽게 말하면 component'태어나는 것'을 의미한다.

먼저 클래스 생성 함수 constructor는 컴포넌트가 mount(시작)될 때, 화면에 표출 될 때, Website에 갈 때, 실행 된다.

그다음 render 함수가 실행 되어 컴포넌트를 렌더링 해준다.

componentDidMount는 render 함수가 실행 된 뒤, 마지막으로 실행된다.

import { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    console.log("constructor");
  }
  state = {
    count: 0,
  };

  add = () => {
    this.setState((current) => ({ count: current.count + 1 }));
  };

  minus = () => {
    this.setState((current) => ({ count: current.count - 1 }));
  };

  componentDidMount() {}

  render() {
    console.log("render");
    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;
리액트 실행 -> constructor -> render -> componentDidMount

Updating

Updating은 리액트에서 일반적인 업데이트가 일어남을 의미한다.

setState로 state 변경이 일어나면 우선 render 함수가 실행 되고

이후로 componentDidUpdate 함수가 실행된다.

import { Component } from "react";

class App extends Component {
  constructor(props) {
    super(props);
    console.log("constructor");
  }
  state = {
    count: 0,
  };

  add = () => {
    this.setState((current) => ({ count: current.count + 1 }));
  };

  minus = () => {
    this.setState((current) => ({ count: current.count - 1 }));
  };

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

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

  render() {
    console.log("render");
    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;
state변경(setState 실행) -> render -> componentDidUpdate

Unmounting

Unmounting은 쉽게 말하면 컴포넌트가 죽는 걸, 떠나는 걸 의미 한다.

컴포넌트가 어떻게 죽냐면 페이지를 바꿀때 or state를 이용해서 렌더 되는 컴포넌트를 바꿀때가 해당 된다.

이때 componentWillUnmount 함수가 실행 된다.

예를 들어서

isLogin이라는 state의 값이 false라면 Login 컴포넌트를,

true라면 MyPage 컴포넌트를 렌더하는 삼항 연산자가 있을 경우

render(){

	return(
	<div>
      {isLogin?<Mypage/>:<Login/>}
    </div>
    )
}

isLogin이 setState로 기본값 false에서 true로 변경 될 때,

Login 컴포넌트에서 MyPage 컴포넌트로 변경 되면서, Login 컴포넌트가 죽었기에

componentWillUnmount 함수가 실행된다.

profile
내가 보려고 쓰는 블로그

0개의 댓글