Table of Contents
Infinite Loading is a technique used for optimizing the performance of rendering an extensive list. It’s a fancy type of pagination, but it listens to scroll events instead of clicking the button. So how to implement it, let’s follow me. Normally we implement Infinite Loading with the scroll event, but in this article, let’s explore a more advanced technique with the Intersection Observer.
Table of Contents
I. Concept
- Intersection Observer instead of Javascript scroll event
- React Hook: handle fetch data and return the state of fetching such as loading, error, data, hasMore
- Api fetch data
II. Code example
Step 1
- Assign ref to only the last item on the rendering list of items
- Create a new IntersectionObserver and observe the dom node. The callback will update the pageNumber state if the dom node is intersecting
- Ref and use Intersection Observer to handle event if ref appears to the viewport (intersecting)
Step 2
Call useFetchData and render list via the below data: ‘banks’ is the list data that includes both old and new items
Demo: https://stackblitz.com/edit/react-ts-h6anar
Link: https://www.youtube.com/watch?v=NZKUirTtxcg
DungNTT