1. 문제 정의

Next.js 프로젝트에서 useEffect를 사용하여 특정 조건이 충족될 때 API 요청을 실행하는 코드가 있을 경우, React Strict Mode가 활성화된 환경에서 useEffect가 개발 모드에서 두 번 실행되는 문제가 발생할 수 있음.

예제 코드:

useEffect(() => {
  if (isVisible && contents.length === 0) {
    fetchLocationList();
  }
}, [isVisible, contents.length, fetchLocationList]);

❌ 문제점


2. 해결 방법: useRef를 활용한 중복 실행 방지

useRef를 사용하여 API 요청이 한 번만 실행되도록 제어할 수 있음.

수정된 코드:

const isFetched = useRef(false);

useEffect(() => {
  if (isVisible && contents.length === 0 && !isFetched.current) {
    isFetched.current = true; // ✅ 첫 실행 후 다시 실행되지 않도록 설정
    fetchLocationList();
  }
}, [isVisible, contents.length, fetchLocationList]);

📌 useRef를 활용하는 이유


3. 코드 설명