특정 페이지 조회 시 Hibernate 무한 루프 이슈

gminnimk·2024년 11월 23일

문제 해결

목록 보기
10/18



Hibernate 무한 루프 이슈




📜 문제 상황

  • Front 에서 WasteRecord 페이지에 액세스하면 반복적인 API 호출이 발생하여 무한 루프가 발생.
  • 클라이언트 네트워크 확인

  • Spring 서버 콘솔 창

Hibernate: select p1_0.id, p1_0.bio, p1_0.created_at, p1_0.modified_at, p1_0.profile_image_url, u1_0.id, u1_0.approval_status, u1_0.created_at, u1_0.email, u1_0.google_id, u1_0.kakao_id, u1_0.modified_at, u1_0.password, u1_0.resigned_at, u1_0.role, u1_0.username from profiles p1_0 left join users u1_0 on u1_0.id=p1_0.user_id where p1_0.user_id=? Hibernate: / select count(wasteRecord) from WasteRecord wasteRecord / select count(wr1_0.id) from waste_records wr1_0 Hibernate: / select count(wasteRecord) from WasteRecord wasteRecord / select count(wr1_0.id) from waste_records wr1_0 Hibernate: / select wasteRecord from WasteRecord wasteRecord order by wasteRecord.createdAt desc / select wr1_0.id, wr1_0.created_at, wr1_0.modified_at, wr1_0.user_id from waste_records wr1_0 order by wr1_0.created_at desc limit ?, ? Hibernate: / select wasteRecord from WasteRecord wasteRecord order by wasteRecord.createdAt desc / select wr1_0.id, wr1_0.created_at, wr1_0.modified_at,




📜 문제 원인


  • React는 함수가 렌더링될 때마다 다시 생성되므로 함수를 종속성으로 취급.

  • 종속성 배열에 'fetchAllRecords'를 포함하면 구성요소가 다시 렌더링될 때마다 'useEffect'가 다시 트리거되어 지속적인 API 호출 루프가 발생.




📜 문제 해결


📄 불필요한 종속성 제거

  • currentPage가 변경될 때마다 fetchAllRecords를 실행할 필요는 없음.

  • 한 번만 필요(예: 초기 로드 시).

  • fetchAllRecords를 한 번만 호출하도록 useEffect를 조정하고 fetchData를 currentPage에만 종속되게 수정.


  • 이전코드
useEffect(() => {
  fetchData(currentPage);
  fetchAllRecords(); // Runs on every `currentPage` change
}, [currentPage], fetchAllRecords); 

  • 업데이트 코드
useEffect(() => {
  fetchData(currentPage);
}, [currentPage]);

useEffect(() => {
  fetchAllRecords();
}, []); 

'useEffect' 종속성을 조정하고 적절한 상황에서 API 호출('fetchData' 및 'fetchAllRecords')이 호출되도록 함으로써 백엔드 로직을 수정하지 않고 무한 API 호출 루프가 해결.

0개의 댓글