⭐ 무한스크롤 함수 아래 페이지 참고

무한 스크롤

// HomePage.tsx
//SECTION - 스크롤 위치 기억

// 스크롤 영역에 대한 ref
const scrollAreaRef = useRef<HTMLDivElement>(null)

// 컴포넌트 마운트 시 항상 최신 데이터 조회 (staleTime이 지난 경우)
useEffect(() => {
  // 페이지 진입 시 항상 최신 데이터 확인
  console.log('홈 페이지 진입: 최신 데이터 확인')
  refetch({ cancelRefetch: false })
}, [refetch])

// 스크롤 이벤트 리스너 등록
useEffect(() => {
  const scrollElement = scrollAreaRef.current
  if (!scrollElement) return

  // 이벤트 리스너 등록 및 클린업 함수 받기
  const cleanup = addScrollListener(scrollElement, SCROLL_KEY)

  return cleanup
}, [])

// 스크롤 위치 복원
useEffect(() => {
  // 새로고침이 아닌 경우에만 스크롤 위치 복원
  const shouldRestoreScroll = !location.state?.refreshFeed

  if (
    scrollAreaRef.current &&
    !isLoading &&
    data?.pages &&
    shouldRestoreScroll
  ) {
    const position = getScrollPosition(SCROLL_KEY)
    if (position > 0) {
      setTimeout(() => {
        if (scrollAreaRef.current) {
          scrollAreaRef.current.scrollTop = position
        }
      }, 200)
    }
  }
}, [data, isLoading, location.state])

⭐ tanstack query, zustand 사용