Error: React Hook useEffect has missing dependencies:...Either include them or remove the dependency array

2024. 8. 19. 02:20·React

 

 

1.  문제 발생

프로젝트를 배포하는 과정에서 ESLint 경고가 많이 떴는데

대부분의 경고는 쉽게 해결이 가능했지만 해당 경고는 해결하는데 몇시간이 걸렸다. 

 

 

 

 

경고 메시지는 다음과 같았다. 

naver 지도에서 마커를 추가하는 기능을 구현하면서 생긴 오류였다.

 

useEffect 훅을 사용할 때 발생할 수 있는 대표적인 문제 중 하나는 의존성 배열(dependency array)과 관련된 경고이며 이 문제는 리액트 훅이 컴포넌트의 상태나 prop이 변경될 때 올바르게 동작하도록 보장하는 데서 비롯된다.

 

 

즉, 이 경고는 useEffect 내에서 사용된 변수나 함수가 의존성 배열에 포함되지 않으면 생기는 경고 이다. 

 

 

useEffect의 기본 형태 

`useEffect`의 기본 형태는 `useEffect(() => { // 실행할 로직 }, [의존성 배열])`이다. 여기서 의존성 배열은 `useEffect` 내부에서 사용하는 외부 상태나 프로퍼티를 의미한다. 이 배열의 값이 변경될 때만 `useEffect`가 실행된다.


하지만 의존성 배열을 잘못 관리하면 예상치 못한 무한 루프에 빠지거나, 필요 이상의 렌더링이 발생할 수 있다. 따라서 의존성 배열을 정확히 관리하는 것이 중요하다.

 

useEffect의 의존성 배열이란?

의존성 배열은 useEffect 훅에 입력하는 두 번째 매개변수이다. 의존성 배열의 내용이 변경되었을 경우 부수 효과 함수가 실행된다. 의존성 배열은 잘못 관리하면 쉽게 버그로 이어지기 때문에 입력하지 않는게 좋지만 필요에 있어 입력할 일이 생긴다.


 

 

 

내가 원래 작성한 코드를 살펴 보자.

//네이버 지도 생성 코드

    useEffect(() => {
        if (currentLocation.lat !== 0 && currentLocation.lng !== 0) {
            const map = new naver.maps.Map('map', {
                center: new naver.maps.LatLng(37.3595704, 127.105399),
            var mapOptions = {
                center: new naver.maps.LatLng(currentLocation.lat, currentLocation.lng),
                zoomControl: true,
                zoomControlOptions: {
                    style: naver.maps.ZoomControlStyle.SMALL,
                    position: naver.maps.Position.TOP_RIGHT,
                },
                zoom: 10,
                mapDataControl: true,
                scaleControl: true,
                maxZoom: 20,
                zoom: 18,
            };
        }
        map = new naver.maps.Map(mapElement.current, mapOptions);
        setNewMap(map);
        addMarkers();
    }, []);

 

이 코드는 네이버 지도 생성 코드였고

   //마커 생성 코드
   const addMarker = (id, name, lat, lng) => {
        try {
            let newMarker = new naver.maps.Marker({
                position: new naver.maps.LatLng(lat, lng),
                map: map,
                title: name,
                clickable: true,
                icon: {
                    content: <img src="/images/location.svg" />,
                },
            });
            console.log('process...');
            newMarker.setTitle(name);
            createMarkerList.push(newMarker);
            naver.maps.Event.addListener(newMarker, 'click', () => markerClickHandler(id));
        } catch (e) {}
    };
    const addMarkers = () => {
        for (let i = 0; i < data.length; i++) {
            let markerObj = data[i];
            const dom_id = markerObj.id;
            const title = markerObj.name;
            const lat = markerObj.latitude;
            const lng = markerObj.longitude;
            addMarker(dom_id, title, lat, lng);
        }
    }, [currentLocation]);

 

마커 생성 코드는 useEffect 밖에 있었다. 

 

2.  해결 방법

 

useEffect 훅 내에서  addMarkers , currentLocation.lat, currentLocation.lng 등...의 변수를 사용 했는데 선언은 useEffect  밖에서 했기 때문에 문제가 되는 것이다.

 

따라서 해결 방법은 두 가지 이다. 

  1. 의존성 배열에 useEffect에서 사용한 모든 변수 추가하기
  2. 해당 변수를 useEffect 내에서 사용하지 않기

 

 

 

'React' 카테고리의 다른 글

제어 컴포넌트 vs 비제어 컴포넌트와 react-hook-form  (0) 2025.01.01
[React + Typescript] : 무한 스크롤 Intersection Observer API  (0) 2024.09.03
React: [Error] Firebase 사용자 photoURL  (0) 2024.01.19
React: Path Parameters  (0) 2023.12.27
node_modules (npm)과 Yarn Berry  (0) 2023.10.30
'React' 카테고리의 다른 글
  • 제어 컴포넌트 vs 비제어 컴포넌트와 react-hook-form
  • [React + Typescript] : 무한 스크롤 Intersection Observer API
  • React: [Error] Firebase 사용자 photoURL
  • React: Path Parameters
hyejeong_02
hyejeong_02
  • hyejeong_02
    프론트엔드 개발일지
    hyejeong_02
  • 전체
    오늘
    어제
    • 분류 전체보기 (24)
      • React (9)
      • 네트워크 (2)
      • git (2)
      • HTML (0)
      • CSS (1)
      • Typescript (1)
      • java script (3)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    useefftect
    js
    redux
    ESLint
    무한스크롤
    controlled
    infiniteScroll
    var와 let의 차이
    react
    react-hook-form
    제어 컴포넌트
    uncontrolled
    얕은 복사
    intersectionObserver
    리렌더링
    useeffect오류
    불변성
    Prettier
    비제어 컴포넌트
    의존성배열
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
hyejeong_02
Error: React Hook useEffect has missing dependencies:...Either include them or remove the dependency array
상단으로

티스토리툴바