React, Next.js

[React] 컴포넌트 생명주기 - Component Life Cycle (with useEffect)

쭈꾸미 2022. 2. 9. 15:16

컴포넌트 생명주기란?

컴포넌트가 브라우저에 나타나고, 업데이트 되고, 사라질 때 호출되는 메소드. 렌더링을 기준으로 특정 시점에 코드가 실행되도록 할 수 있다. 클래스형 컴포넌트로 선언시에만 사용 가능하며 함수형에서 생명주기를 사용하고 싶은 경우에는 훅(Hook)을 이용해 유사하게 구현해야 한다.

  1. 그리기 : render()
  2. 그리고 난 뒤 : componentDidMount()
  3. 그리고 난 뒤 업데이트 : componentDidUpdate()
  4. 그리고 난 뒤 사라짐 : componentWillUnmount()

 

생명주기는 이런 형태로 사용된다. (예시의 경우 Next.js 환경)

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

export default class ClassCounterPage extends Component {
  inputRef = createRef();
  state = {
    count: 0,
  };

  componentDidMount() {
    console.log("마운트됨!!");
    this.inputRef.current?.focus();
  }

  componentDidUpdate() {
    console.log("수정되고 다시 그려짐!!");
  }

  componentWillUnmount() {
    console.log("여기서 나갈래요~");
  }

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

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

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

 

그렇다면 함수형에서는?

함수형에서는 리액트 Hook 중 하나인 useEffect()를 사용해서 생명주기의 기능을 유사하게 구현할 수 있다.

useEffect는 컴포넌트가 그려진 이후에 실행되는 함수이다.

  // 1. componentDidMount와 동일하다.
  useEffect(() => {
    console.log("마운트됨!!");

    // 2. componentWillUnmount와 동일하다.
    return () => {
      console.log("여기서 나갈래요~");
    };
  }, []); // 이 빈 배열을 의존성 배열(dependency array)이라고 부른다.
  // 빈 의존성 배열을 넣어주면 화면이 그려질때 단 한 번만 실행된다.

  // 3. componentDidUpdate와 비슷하다. (동일하지는 않음)
  useEffect(() => {
    console.log("수정되고 다시 그려짐!!");
  });
  // 의존성 배열이 들어가있지 않은 경우, 무엇이든 바뀌면 실행된다.

 

useEffect 사용시, 의존성 배열에 특정 state값을 넣어주면 해당 state가 변경되었을 때 화면이 다시 그려지도록 할 수 있다.

  useEffect(() => {
    console.log("count값이 변경되었습니다!");
  }, [count])