[Codecamp-Week4] State Lifecycle

·2022년 7월 26일
0

이전 글에선 functional component와 class component를 알아보았다.

글에 언급한 것처럼 이번 블로그에선 state lifecycle(생명주기)에 대해 살펴보도록 하자!
(처음에 생명주기란 말을 듣고선 '그럼 state가 죽으면 다시 살려줘야되는 기간이 있는건가..?' 란 헛생각을 또 하고 말았다.)

1. State Lifecycle이란?

state lifecycle (생명주기)란 컴포넌트가 브라우저에 나타나고, 업데이트 되고, 사라질 때 호출되는 method이다.
특정 시점에 코드가 실행되도록 설정할 수 있는 것을 의미한다.

<출처 : https://www.zerocho.com/category/React/post/579b5ec26958781500ed9955>

2. lifecycle

1) lifecycle?

class component lifecycle은 크게 네 가지로 나눠볼 수 있다.

(1) render : 나타내기

이전 블로그에서 본 것처럼 브라우저에 컴포넌트를 나타내기 위해서 render를 사용한다.

(2) componentDidMount: 나타낸 후 실행

render를 통해 rendering이 끝나고 난 후 실행된다.

(3) componentDidUpdate: 나타낸 후 변경되면 실행

rendering이 끝난 후 rendering 화면이 변경되면 실행된다.

(4) componentWillUnmount: 나타낸 후 사라지면 실행

rendering된 화면에서 빠져나가게 되면 실행된다.

2) lifecycle 살펴보기

사실 이렇게 나열해놔도 느낌이 전혀 오질 않는다.
코드를 통해 살펴보자!

이전 글처럼 버튼을 누르면 1씩 증가하는 컴포넌트를 생성하였으며, 거기에 추가적으로 localhost:3000 으로 빠져나가는 버튼을 하나 만들어주었다.

콘솔을 살펴볼 경우, componentDidMount는 랜더링 후 바로 찍히고 componentDidUpdate는 카운트 올리기 버튼을 누르면 찍힌다. 나가기 버튼을 누르면 componentWillUnmount가 찍히는 것을 볼 수 있다.

import { Component } from "react";
import Router from "next/router";

export default class ClassCounterPage extends Component {
  state = {
    count: 0,
  };

  componentDidMount() {
    console.log("그려지고 나서 실행!");
  }

  componentDidUpdate() {
    console.log("변경되고 나서 실행!");
  }

  componentWillUnmount() {
    console.log("사라질 때 실행!");
    // 채팅방 나가기 API 요청
  }

  counterUp = () => {
    console.log(this.state.count);
    this.setState({
      count: 1,
    });
  };

  onClickMove() {
    Router.push("/");
  }

  render() {
    return (
      <>
        <div>{this.state.count}</div>
        <button onClick={this.counterUp}>카운트 올리기!</button>
        <button onClick={this.onClickMove}>나가기!</button>
      </>
    );
  }
}
profile
개발을 개발새발 열심히➰🐶

0개의 댓글