summaryrefslogtreecommitdiff
path: root/apps/web/src/hooks/use-infinite-scroll.ts
blob: 0f8db198b8f3124c26ad452ae04394f689e1b81b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { useRef, useCallback } from "react";

interface UseInfiniteScrollOptions {
  onLoadMore: () => void;
  hasMore: boolean;
  isLoading: boolean;
  threshold?: number;
  enabled?: boolean;
}

export function useInfiniteScroll({
  onLoadMore,
  hasMore,
  isLoading,
  threshold = 200,
  enabled = true,
}: UseInfiniteScrollOptions) {
  const scrollAreaRef = useRef<HTMLDivElement>(null);

  const handleScroll = useCallback(
    (event: React.UIEvent<HTMLDivElement>) => {
      if (!enabled) return;

      const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
      const nearBottom = scrollTop + clientHeight >= scrollHeight - threshold;

      if (nearBottom && hasMore && !isLoading) {
        onLoadMore();
      }
    },
    [onLoadMore, hasMore, isLoading, threshold, enabled]
  );

  return { scrollAreaRef, handleScroll };
}