로고로고

useEmotionLogToday 무한 마운트

2025년 4월 1일

리액트 쿼리가 무한히 재요청하며 마운트가 반복되는 현상 발생

 

useQuery({
  queryKey: ['emotionLogToday', userId],
  queryFn: () => (userId ? getEmotionLogToday({ userId }) : Promise.resolve(null)),
  enabled: userId !== null,
});

 

  • userId가 존재할 때만 쿼리가 실행되도록 enabled 조건이 걸려 있었음
  • 하지만 useSession에서 user 정보를 비동기로 받아오므로, 초기 렌더링 시 userId가 undefined였다가 나중에 값이 생김
  • 이 상태에서 리액트 쿼리는 해당 쿼리를 다시 mount할 때마다 자동으로 재요청(retryOnMount)을 시도

즉, enabled와 queryKey 조건이 계속 바뀌면서 쿼리 재요청 → 상태 업데이트 → 재렌더링 → 다시 쿼리 재요청…

 

useQuery({
  queryKey: ['emotionLogToday', userId],
  queryFn: () => (userId ? getEmotionLogToday({ userId }) : Promise.resolve(null)),
  enabled: userId !== null,
  retryOnMount: false, 
});

retryOnMount: false는 쿼리가 에러 상태일 때 컴포넌트가 다시 마운트되어도 재요청하지 않도록 막는 설정

이걸 추가함으로써 리액트 쿼리가 컴포넌트가 재마운트될 때마다 다시 쿼리를 보내는 것을 방지

 

내용
문제useEmotionLogToday에서 무한 마운트 현상 발생
원인React Query가 userId 변경 시마다 retryOnMount로 재요청 반복
해결retryOnMount: false 설정으로 마운트 시 재요청 방지
결과무한 루프 멈추고 정상 렌더링 가능