SoFunction
Updated on 2025-04-07

react scroll load useInfiniteScroll Detailed explanation

  useInfiniteScroll is a custom React Hook to simplify the task of implementing infinite scrolling capabilities in React components.

The basic idea of ​​infinite scrolling is that we do not load all data at once, but gradually load the data as the user scrolls down the page. This gives the user the feeling of endless content list without waiting for all the data to load at once.

        Use the useInfiniteScroll hook can handle logic that detects when a user scrolls to the bottom of the page and triggers a callback function to load more data. It also provides an easy way to manage the state of loading and error messages.

Here are some specific instructions for useInfiniteScroll:

1: Parameters:

useInfiniteScroll accepts a callback function as a parameter, which should be an asynchronous function to avoid blocking the user interface. When the user scrolls to the bottom of the page, useInfiniteScroll automatically calls the callback function to load more data. The callback function should return a Promise to use the async/await syntax. For example:

const loadMoreData = async () => {
  // Logic for loading more data  const response = await fetch('/api/data?page=2');
  const newData = await ();
  return newData;
};
const [isFetching, setIsFetching] = useInfiniteScroll(loadMoreData);

The callback function can return any type of data, such as arrays, objects, etc., depending on the needs of your application. When using loaded data in a component, we usually need to store it in state for rendering, like so:

function MyComponent() {
  const [data, setData] = useState([]);
  const [isFetching, setIsFetching] = useInfiniteScroll(loadMoreData);
  const handleLoadData = async () => {
    const newData = await loadMoreData();
    setData(prevData => [...prevData, ...newData]);
  };
  return (
    <div>
      {/* Rendering data list */}
      {(item => <div key={}>{}</div>)}
      {/* Show loading indicator */}
      {isFetching && <div>Loading more data...</div>}
    </div>
  );
}

Two: Return value:

useInfiniteScroll returns a boolean value and a function. Boolean values ​​indicate whether the user is currently scrolling, and the function is used to enable or disable infinite scrolling.

  • isFetching: A boolean value indicating whether more data is being loaded.
  • setIsFetching: A function that can be used to manually set the value of isFetching.

IsFetching can be used to display the loading indicator so that the user knows that the data is being loaded. For example, in the above example, when loading more data, we used isFetching to display the "loading" text as follows:

{isFetching && <div>Loading more data...</div>}

When the data is loaded, isFetching will be automatically set to false.

Three: Use:

Using useInfiniteScroll in components is simple. Just call useInfiniteScroll within the component and pass the callback function as a parameter. As shown below:

import useInfiniteScroll from './useInfiniteScroll';
function MyComponent() {
  const loadMoreData = async () =&gt; {
    // Logic for loading more data  };
  const [isFetching, setIsFetching] = useInfiniteScroll(loadMoreData);
  return (
    &lt;div&gt;
      {/* Rendering data list */}
    &lt;/div&gt;
  );
}

Four: Component status:

When using useInfiniteScroll, we also need to manage the status of the component, such as: whether data is being loaded, whether there is an error, etc. Therefore, some state variables are usually required to be defined within components that useInfiniteScroll to track these states.

The status of useInfiniteScroll component includes:

  • Whether the data has been loaded.
  • Current page number.
  • Whether the data is being loaded.

The status of whether the data has been loaded is usually provided by the backend, and it can be determined by determining whether there is a next page in the return data.

The current page number status can be determined based on the page number parameters passed each time the data is loaded.

Whether the data is loading can be expressed using isFetching status. When the data is loading, isFetching is true and false after loading.

Five: Custom options:

useInfiniteScroll also allows us to pass some custom options to customize its behavior. For example, we can specify the scroll trigger distance, initial state, etc.

Here are some common options:

  • threshold: indicates the number of pixels required from the bottom of the window to the next request, the default value is 0.
  • hasMore: Indicates whether there is more data, if set to false, the load event will not be triggered again.
  • loader: represents the component displayed when data is loading.
  • useCapture: Indicates whether events are executed during the capture phase, default is false.

In addition, you can also customize the parameters, request headers, request methods, etc. that need to be passed each time the data is loaded. Specifically, all configurations that can be used in the fetch API can be used. For more information, see the section on Custom Hooks in the React documentation.

Here is a simple example:

​
import { useState, useEffect } from 'react';
import useInfiniteScroll from './useInfiniteScroll';
function MyComponent() {
  const [data, setData] = useState([]);
  const [page, setPage] = useState(1);
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState(null);
  const loadMore = async () => {
    setIsLoading(true);
    try {
      const newData = await fetch(`/data?page=${page}`);
      setData((newData));
      setPage(page + 1);
    } catch (e) {
      setError();
    }
    setIsLoading(false);
  };
  const [isFetching, setIsFetching] = useInfiniteScroll(loadMore);
  return (
    <div>
      {(item => (
        <div key={}>{}</div>
      ))}
      {isLoading && <div>Loading...</div>}
      {error && <div>{error}</div>}
    </div>
  );
}
​

In this example, we have a component that displays a list of data loaded from the API endpoint. When the user reaches the bottom of the page, call the loadMore function to get the data for the next page.

Use the useInfiniteScroll hook to detect when the user reaches the bottom of the page and trigger the loadMore function. Use the setIsFetching function to manage the state of the hook and track whether the user is currently scrolling.

The isLoading and error status variables are used to display loading rotator and error messages when loading data.

This is the end of this article about react scroll loading useInfiniteScroll. For more related react scroll loading content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!