Infinite Scroll with Search UI React

Recently, someone sent me a Slack message asking how to fetch search results when scrolling to the bottom of a page, rather than using a pagination component. This method is commonly referred to as infinite scroll. I put together this Code Sandbox that demonstrates how to accomplish infinite scroll with Search UI React.

I want to highlight a few key points about this implementation:

  • Rather than use the VerticalResults component that is tightly coupled with the Search Headless vertical results, I am mapping over results stored in the component state.
  • When you set a function as an event listener using addEventListener , the function will use the state and props that were present at the time it was created. Therefore, to ensure that the event listener function has access to the latest state and props, I am using a technique called “closing over” the state and props using the useCallback hook.
  • searchLoading needs to be added to the useCallback dependency array to ensure that the same page of results are not fetched twice