React/React Core

5.React 컴포넌트 생명주기 완벽 이해: Lifecycle Methods의 모든 것

코딩쉐프 2024. 11. 22. 15:59
728x90

React 컴포넌트 생명주기 완벽 이해: Lifecycle Methods의 모든 것


1시간 분량 강의안 (Lifecycle Methods 기초)

강의 목표

  1. React 컴포넌트의 생명주기와 각 단계의 특징을 이해한다.
  2. 클래스형 컴포넌트의 Lifecycle Methods를 학습한다.
  3. 함수형 컴포넌트에서 생명주기를 관리하는 방법(Hooks)을 이해한다.

강의 목차


1. React 컴포넌트 생명주기란? (10분)

생명주기(Lifecycle)의 정의

  • React 컴포넌트는 생성 → 업데이트 → 소멸의 과정을 거칩니다.
  • 생명주기 메서드는 컴포넌트의 특정 시점에서 실행되는 메서드입니다.

생명주기의 주요 단계

  1. Mounting (생성):
    • 컴포넌트가 DOM에 추가될 때 호출됩니다.
    • 주요 메서드: constructor, render, componentDidMount
  2. Updating (업데이트):
    • 컴포넌트의 Props나 State가 변경될 때 호출됩니다.
    • 주요 메서드: shouldComponentUpdate, render, componentDidUpdate
  3. Unmounting (소멸):
    • 컴포넌트가 DOM에서 제거될 때 호출됩니다.
    • 주요 메서드: componentWillUnmount

2. 클래스형 컴포넌트에서 Lifecycle Methods 사용법 (25분)

1단계: Mounting 단계

  1. constructor:
    • 컴포넌트를 초기화하는 단계에서 호출.
    • State와 Props를 초기화.
    constructor(props) {
      super(props);
      this.state = { count: 0 };
    }
    • render:
    • 컴포넌트를 화면에 렌더링.
    • 반드시 순수 함수여야 하며, UI를 반환.
      render() {
        return <h1>Hello, React!</h1>;
      }
  2. componentDidMount:
    • 컴포넌트가 DOM에 추가된 직후 호출.
    • API 호출, 이벤트 리스너 등록 등에 사용.
     
componentDidMount() {
  console.log("Component mounted!");
}

2단계: Updating 단계

  1. shouldComponentUpdate:
    • 컴포넌트가 업데이트될지 여부를 결정.
    • 성능 최적화에 유용.
    shouldComponentUpdate(nextProps, nextState) {
      return nextState.count !== this.state.count;
    }
  2. componentDidUpdate:
    • 컴포넌트가 업데이트된 후 호출.
    • DOM 작업, API 호출 등에 사용.
     
componentDidUpdate(prevProps, prevState) {
  console.log("Component updated!");
}

3단계: Unmounting 단계

  1. componentWillUnmount:
    • 컴포넌트가 DOM에서 제거되기 직전에 호출.
    • 정리(clean-up) 작업에 사용.
     
componentWillUnmount() {
  console.log("Component will unmount!");
}

3. 함수형 컴포넌트에서 생명주기 관리 (15분)

Hooks를 사용한 생명주기 관리

  • 함수형 컴포넌트는 Lifecycle Methods 대신 useEffect Hook을 사용합니다.
  • useEffect는 다음과 같은 역할을 합니다:
    1. componentDidMount
    2. componentDidUpdate
    3. componentWillUnmount

1단계: 기본 useEffect 사용

import React, { useState, useEffect } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component mounted or updated!");
  });

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

export default Counter;

2단계: Clean-up 작업

  • componentWillUnmount와 동일한 역할을 수행.
import React, {useState, useEffect} from "react"

function Counter() {

useEffect(() => {
  const interval = setInterval(() => {
    console.log("Tick");
  }, 1000);

  return () => {
    clearInterval(interval);
    console.log("Component will unmount!");
  };
}, []);

}

export default Counter;
Console 출력 화면

4. 실습 과제 (10분)

실습 과제

  1. componentDidMount를 사용하여 컴포넌트가 로드될 때 콘솔 메시지를 출력하세요.
  2. useEffect를 사용하여 타이머를 구현하고 컴포넌트가 제거될 때 타이머를 정리하세요.

예제

// src/components/timer.js

import React, {useState, useEffect} from "react"

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds((prev) => prev + 1);
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return <p>Seconds: {seconds}</p>;
}

export default Timer;

5. Q&A 및 정리 (10분)

  • Q&A:
    1. Lifecycle Methods와 useEffect의 차이는 무엇인가요?
    2. 어떤 경우에 componentWillUnmount가 중요한가요?
  • 요약:
    • React 컴포넌트는 Mounting, Updating, Unmounting 단계로 나뉩니다.
    • 클래스형 컴포넌트에서는 생명주기 메서드를 사용하고, 함수형 컴포넌트에서는 useEffect를 사용합니다.
    • 생명주기는 컴포넌트의 상태 관리와 동작을 제어하는 데 중요한 역할을 합니다.
728x90