Lifecycle

mangjell·2022년 4월 9일
0

class 컴포넌트의 생명주기(Life Cycle)

컴포넌트의 생명주기는 컴포넌트가 브라우저에 나타나고 업데이트 되고, 사라지게 될 때 호출되는 메서드 이다.

쉽게 말해, 특정 시점에 코드가 실행되도록 설정할 수 있다는 것이다.

메서드에 대해 간략히 요약한다면,

  1. 그리기 → render 인풋창 그리기
  2. 그리고 난 뒤 → componentDidMount포커스 깜빡 깜빡 하기
  3. 그리고 난 뒤 변경 → componentDidUpdate
  4. 그리고 난 뒤 사라짐 → componentWillUnmount

아래의 예시는 class component 생명주기이다.

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

interface IState {
  count: number;
}

export default class CounterPage extends Component {
  inputRef = createRef<HTMLInputElement>();
  state = {
    count: 0,
  };

  // 라이프 사이클 부분
  componentDidMount() {
    console.log("마운트됨!!");
    this.inputRef.current?.focus(); // 화면에 커서가 깜빡깜빡하게끔!!
    // 포커스 깜빡깜빡
  }

  // 라이프 사이클 부분
  componentDidUpdate() {
    console.log("수정되고 다시그려짐!");
  }

  // 라이프 사이클 부분
  componentWillUnmount() {
    console.log("컴포넌트 사라짐!");
    // 채팅방 나가기
    // api 요청!
  }

  onClickCounter = () => {
    console.log(this.state.count);
    this.setState((prev: IState) => ({
      count: prev.count + 1,
    }));
  };

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

  render() {
    return (
      // 방법 - 1
      <div>
        <input type="text" ref={this.inputRef} />
        <div>현재 카운트: {this.state.count}</div>
        <button onClick={this.onClickCounter}>카운트 올리기!</button>
        <button onClick={this.onClickMove}>나가기 버튼!!</button>
      </div>
    );
  }
}

반면에, 아래는 functional component 생명주기이다.

import { Component, createRef, useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";

interface IState {
  count: number;
}

export default function CounterPage() {
  const router = useRouter();
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("수정되고 다시그려짐!");
  }, [count]);


  // 4. DidMount와 WillUnmount를 합치기!!
  useEffect(() => {
    console.log("마운트됨!!");
    inputRef.current?.focus();

    return () => {
      console.log("컴포넌트 사라짐!");
    };
  }, []); // 의존성 배열 (dependency array) 함수가 실행될지 안될지 의존한다

  const onClickCounter = () => {
    setCount((prev) => prev + 1);
  };

  const onClickMove = () => {
    router.push("/");
  };

  console.log("나는 언제 실행되게?");

  return (
    <div>
      <input type="text" ref={inputRef} />
      <div>현재 카운트: {count}</div>
      <button onClick={onClickCounter}>카운트 올리기!</button>
      <button onClick={onClickMove}>나가기 버튼!!</button>
    </div>
  );
}
  • 훨씬 편리하다. 함수형 컴포넌트 생명주기!!
  • useEffect, useRef는 다음에 다뤄보도록 하자!
profile
프론트엔드 개발자

0개의 댓글