Install

npm
npm i use-any-hook

Description

The useInfiniteScroll hook simplifies the implementation of infinite scrolling in your React application. It allows you to load more data automatically as the user scrolls to the bottom of the page or a container. This hook is particularly useful for applications that need to fetch and display a large dataset in chunks, improving both performance and user experience.

Parameters

NameTypeDescription
loadMore() => voidA function to be called when more data needs to be loaded. This function should handle the data fetching logic.

Return Values

NameTypeDescription
isFetchingbooleanA boolean indicating whether the hook is currently fetching more data. This can be used to show loading indicators.

Example

useInfiniteScroll.example.tsx
import { useInfiniteScroll } from "use-any-hook";

function InfiniteScrollExample() {
  const [items, setItems] = useState([]);
  const [page, setPage] = useState(1);

  // Simulated function to fetch more data
  const fetchMoreData = async () => {
    // Simulated API call to fetch more items (e.g., from a backend server)
    const response = await fetch(`https://api.example.com/items?page=${page}`);
    const newData = await response.json();

    // Update the items and page
    setItems([...items, ...newData]);
    setPage(page + 1);
  };

  const isFetching = useInfiniteScroll(fetchMoreData);

  useEffect(() => {
    // Initial data fetch when the component mounts
    fetchMoreData();
  }, []);

  return (
    <div>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
      {isFetching && <p>Loading more items...</p>}
    </div>
  );
}