코딩기록

리액트) React의 hook, useEffect() 의존성 배열이 있을때, 없을때 본문

프론트/리액트

리액트) React의 hook, useEffect() 의존성 배열이 있을때, 없을때

뽀짝코딩 2025. 1. 7. 20:35
728x90

 

useEffect는 React의 훅(hook) 중 하나로, **부수 효과(side effects)**를 처리하기 위해 사용된다.

컴포넌트가 렌더링된 후 특정 작업을 수행하거나, 상태나 props의 변경에 따라 동작을 정의할 수 있게 해준다. 클래스형 컴포넌트에서 사용했던 생명주기 메서드(componentDidMount, componentDidUpdate, componentWillUnmount)를 대체하는 역할을 한다.

 

특징

1. 의존성 배열에 따라 동작

2. 클린업(Cleanup)

  • 반환값으로 클린업 함수를 정의할 수 있음.
  • 이는 주로 이벤트 리스너 제거, 타이머 정리, 구독 취소 등에 사용.
import React, { useState, useEffect } from 'react';

export default function FunctionClock() {
  const [date, setDate] = useState(new Date());

  function tick() {
    setDate(new Date());
  }

  useEffect(() => {
    console.log("처음 한번만 실행됨 componentDidMount");
    const timerId = setInterval(tick, 1000);

    return () => {
      console.log("언마운트 시 실행됨 componentWillUnmount");
      clearInterval(timerId);
    };

  }, []);

  useEffect(() => {
    console.log("date 업뎃시마다 실행됨componentDidUpdate");
    console.log(date);
  }, [date]);


  return (
    <div>
      <h1>Hello, world!</h1>
      <h1>It is {date.toLocaleTimeString()}.</h1>
    </div>
  );
};

 

전체 코드 흐름 요약

  1. 초기 렌더링 시:
    • 첫 번째 useEffect 실행: "componentDidMount" 로그 출력 → setInterval 시작.
    • 두 번째 useEffect는 실행되지 않음 (date 상태는 변경되지 않았기 때문).
  2. 매 1초마다 (setInterval 실행 시):
    • tick 함수 호출 → setDate로 date 상태 업데이트.
    • 두 번째 useEffect 실행: "componentDidUpdate" 로그 출력 → 새로운 date 값 출력.
  3. 컴포넌트 언마운트 시:
    • 첫 번째 useEffect의 클린업 함수 실행:
      • "componentWillUnmount" 로그 출력.
      • clearInterval(timerId)로 setInterval 종료.

 

 

useEffect() 정리

빈 의존성 배열 ( [ ] ) - 마운트시 한 번만

useEffect는 컴포넌트가 처음 마운트될 때(한 번만) 실행

useEffect(() => {
  console.log("componentDidMount");
}, []);

 

 

값이 있는 의존성 배열 ( [date] )

배열에 포함된 date 값이 변경될 때마다 useEffect가 실행

useEffect(() => {
  console.log("componentDidUpdate");
  console.log(date);
}, [date]);

 

 

의존성 배열이 아예 없을 경우 - 모든 렌더링

해당 useEffect가 컴포넌트가 리렌더링될 때마다 실행

useEffect(() => { console.log("useEffect 실행"); });

 

 

 

  • useEffect는 React 컴포넌트에서 부수 효과(side effects)를 처리하기 위한 훅.
  • 의존성 배열을 활용하여 마운트, 업데이트, 언마운트 시기를 제어할 수 있음.
  • 주요 사용 사례는 데이터 페칭, 타이머 설정, 이벤트 리스너 등록/해제 등.

 

 

클래스형 컴포넌트와의 비교

클래스형 컴포넌트 메서드useEffect로 대체

componentDidMount useEffect(() => {}, []);
componentDidUpdate useEffect(() => {}, [dependencies]);
componentWillUnmount return () => { cleanup } in useEffect

 

 

 

 

 

참고

쳇지피티, 제로베이스강의

 

 

반응형
Comments