I have gone back to an app that I built using Spotify API because they have messed around with all sorts of things a basic app relies on, but that's another article!
The infinite loading hook
Something I was pleased with when returning though was how I had implemented infinite scrolling for the playlists and playlist tracks. Essentially I have used TanStack-Query's useInfiniteQuery() to collect 'pages' of data. A page can essentially be thought of as an object that has various properties including offset, limit, next, previous, and of course the items themselves. It tracks where abouts you are within the data collection. The fetching is quite confusing when you read it without checking out the documentation linked above but essentially the functions that you define for getNextPageParam etc are used internally by the TanStack query function and the merged function just makes sure your items are all in one array (items). I added some JSDocs to remind me of what is going on so I'll just share the whole hook and then show how I've used it in my project (isLoggedIn() is just a simple check but stops query functions from trying to execute if it's definitely going to fail and it's called use*Paginated*Fetch because it started life being used with next/prev buttons btw) -
//I've added the rest operator so that we can pass in extra arguments if needed, such as an id for using it with the playlist tracks functionality import { useMemo } from 'react'; import { useInfiniteQuery } from '@tanstack/react-query'; import { isLoggedIn } from '../services/apiSpotify'; // fetchFunction(pageOffset, limit, ...args) => returns a Spotify page object { items, next, previous, limit, offset, ... } /** * @template T * @typedef {Object} SpotifyPage * @property {string} href - A link to the Web API endpoint returning the full result of the request. * @property {T[]} items - The requested data items. * @property {number} limit - The maximum number of items in the response (as set in the query or by default). * @property {string | null} next - URL to the next page of items, or null if none. * @property {number} offset - The offset of the items returned (as set in the query or by default). * @property {string | null} previous - URL to the previous page of items, or null if none. * @property {number} total - The total number of items available to return. * / /** * @typedef {Object} RawPageObject * @property {number} offset - The index of the first item in the Page object relative to the entire collection of items * @property {number} limit - The maximum number of items in the Page object ( namely items from offset to offset + limit) */ /** * A function that fetches a page of data from the Spotify API, which can optionally take additional arguments as an array * * @template T * @template {any[]} [TArgs=any[]] * @callback FetchingFunction * @param {number} offset - The offset for pagination. * @param {number} limit - The number of items to fetch. * @param {TArgs} [args] - Array of additional arguments passed from usePaginatedFetch. * @returns {Promise<SpotifyPage<T>>} - A promise that resolves to a Spotify page object. */ /** * @template T * @typedef {Object} UsePaginatedFetchResult * @property {SpotifyPage<T> | undefined} data - Merged page object containing flattened items across all loaded pages. * @property {(direction: number) => Promise<void>} getNextPrev - Fetches the next page when direction > 0, or the previous page when direction < 0. * @property {boolean} hasNext - Whether a next page is available to fetch. * @property {boolean} hasPrevious - Whether a previous page is available to fetch. * @property {boolean} isLoading - True during the initial load or any subsequent page fetch. * @property {import('@tanstack/react-query').UseInfiniteQueryResult['refetch']} refetch - Function to manually refetch all loaded pages. */ /** * Custom hook that implements paginated fetching using tanstack-query's useInfiniteQuery. It works alongside the useIntersection custom hook to enable infinite scrolling functionality. This is not for use with cursor pagination!! * * @template T * @template {any[]} [TArgs=any[]] * @param {FetchingFunction} fetchFunction - The api calling function, for example getUserPlaylists or getPlaylistTracks * @param {SpotifyPage | RawPageObject | null} initialState - offset defaults to 0, limit defaults to 20 * @param {...TArgs} args - Additional arguments passed through to the fetchFunction, for example for Playlist tracks we pass in the playlistId * @returns {UsePaginatedFetchResult<T>} - An object containing the merged data (which has an items property that contains all of the pages items for example all the track objects in a playlist), pagination functions, and loading state. */ export function usePaginatedFetch(fetchFunction, initialState, ...args) { const initialOffset = Number(initialState?.offset ?? 0); const limit = Number(initialState?.limit ?? 20); // when args is the playlistId for example this makes the query key unique to that playlist so that the infinite query is cached separately for each playlist const queryKey = [fetchFunction.name || 'paginated', ...args]; const query = useInfiniteQuery({ queryKey, queryFn: ({ pageParam = initialOffset }) => fetchFunction(Number(pageParam), limit, args), getNextPageParam: (lastPage) => { const nextUrl = lastPage?.next; if (!nextUrl) return undefined; const next = new URL(nextUrl).searchParams.get('offset'); return next ? Number(next) : undefined; }, getPreviousPageParam: (firstPage) => { const prevUrl = firstPage?.previous; if (!prevUrl) return undefined; const prev = new URL(prevUrl).searchParams.get('offset'); return prev ? Number(prev) : undefined; }, initialData: initialState ? { pages: [initialState], pageParams: [initialOffset] } : undefined, keepPreviousData: true, enabled: enabledCheck, useErrorBoundary: true, }); // when the query data changes this creates the object that is returned as data from this hook. It essentially extracts all of the items from the Spotify page objects and creates the array that we can map over in the component (for example the tracks in a playlist). If we've started with eg offset 20 and limit 20 then first will have a previous property and obviously last will have a next property until we reach the end of the collection. const merged = useMemo(() => { if (!query.data) return initialState; const pages = query.data.pages; const items = pages.flatMap((p) => p.items || []); const first = pages[0] || {}; const last = pages[pages.length - 1] || {}; return { ...first, items, next: last.next, previous: first.previous, limit, offset: Number(last.offset ?? first.offset ?? 0), }; }, [query.data, initialState, limit]); const getNextPrev = async (direction) => { if (direction > 0 && query.hasNextPage) { await query.fetchNextPage(); } else if (direction < 0 && query.hasPreviousPage) { await query.fetchPreviousPage(); } }; return { data: merged, getNextPrev, hasNext: Boolean(query.hasNextPage), hasPrevious: Boolean(query.hasPreviousPage), isLoading: query.isLoading || query.isFetching, refetch: query.refetch, }; } Triggering loading the next page
The next step is getting more to load as you come towards the end of the currently loaded items. There are packages available for this but it was a massive learning project so I decided to simply incorporate the browser's native IntersectionObserver API and keep it simple but reusable. As you probably already know React's useRef can be used to hold state that doesn't trigger a re-render or, as in this case, to hold a reference to a component or HTML element (stored in .current remember). Again I added some JSDocs so I think this explains itself -
import { useCallback, useEffect, useRef } from 'react'; /** * * @param {Function} callbackFn - function to execute on intersection with arguments of target element and observer object eg callback(target, observer) * @param {Object} options - default: none - same as options object detailed here https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API except that the root is always the viewportElementRef or if not set then it is the browser viewport * @param {Boolean} singleUse - default: true - whether to remove the observer after it has first triggered the callbackFn (ie when using it for infinite scroll loading you'll want it to only trigger once when it first comes into view) * @typedef {Object} Refs * @property {React.Ref} intersectionTargetRef - attach this to the element that you are tracking the intersection of - ie when observing a div it would be <div ref={intersectionTargetRef}></div> * @property {React.Ref} viewportElementRef - defaults to the browser viewport but can be any element so it would trigger the callback when intersectionTargetRef element entered the element with this ref attached (MUST BE AN ANCESTOR OF THE TARGET ELEMENT) * @returns {Refs} An object containing the refs to attach to the element to be observed and optionally the ancestor element to behave as the viewport */ export function useIntersection(callbackFn, options = {}, singleUse = true) { const intersectionTargetRef = useRef(null); const viewportElementRef = useRef(null); const observerCallback = useCallback( (entries, observer) => { const target = entries[0]; if (target.isIntersecting) { callbackFn(target, observer); if (singleUse) { observer.unobserve(target.target); } } }, [callbackFn, singleUse], ); //if no viewportElement is set then it will be null which will make it default to the browser window. This executes whenever the refs are assigned to a new component, or a callback function is assigned, and clears up the listeners when it unmounts (the return function of useEffect remember) useEffect(() => { let observer; const intersectionTarget = intersectionTargetRef?.current; if (intersectionTarget) { const optionsObj = { ...options, root: viewportElementRef?.current, }; observer = new IntersectionObserver(observerCallback, optionsObj); observer.observe(intersectionTarget); } return () => { if (intersectionTarget) { observer.unobserve(intersectionTarget); } observer?.disconnect(); }; }, [intersectionTargetRef, viewportElementRef, observerCallback, options]); return { intersectionTargetRef, viewportElementRef }; } Usage inside a component
With all of that in place here's an example of it being used. This is the React Component that gets and displays the logged in user's playlists and doesn't have a React-Router loader collecting the first page so we simply pass null as the initialState but it shows how simple implementing this functionality is.
import { getUserPlaylists } from '../services/apiSpotify'; import { useCallback } from 'react'; import PlaylistItem from '../ui/PlaylistItem'; import { usePaginatedFetch } from '../query-hooks/usePaginatedFetch'; import Spinner from '../ui/Spinner'; import { useIntersection } from '../hooks/useIntersection'; function Playlists() { // set up the infinite loader const { data: playlists, getNextPrev, hasNext, isLoading, } = usePaginatedFetch(getUserPlaylists, null); // trigger loading the next page when the 4th from last current item enters the viewport let infiniteScrollElementIndex = playlists?.items?.length - 4; // useCallback to track changes to the state const intersectionCallback = useCallback(() => { if (hasNext && !isLoading) { console.log(`I'm loading more of the list`); getNextPrev(1); } }, [isLoading, getNextPrev, hasNext]); // threshold so it triggers when the list component is half in the viewport and delay just to give a bit of breathing room const options = { rootMargin: '0px', scrollMargin: '0px', threshold: 0.5, delay: 20, }; // grab the ref so we can assign it to our list item const { intersectionTargetRef } = useIntersection( intersectionCallback, options, ); return ( <div> <div className="list-container"> <h2>Your Playlists</h2> <div className="playlist-list-table"> <div className="list-header list-row"> <div className="col-title">Title</div> {/* can't access this info from the web api :/ */} {/* <div className="col-playlist-added">Date added</div> */} <div className="col-playlist-tracks">Tracks</div> </div> {playlists?.items.map((item, index) => { // check for tiny playlists and the possibility of item or items being null because they have been removed....I think is what Spotify docs is saying!? Also now item.items as item.tracks is deprecated if ((item?.items?.total ?? 0) < 2) { --infiniteScrollElementIndex; return null; } // link the single item to the ref (remember that this should be a React.forwardRef component if using React 18 or less) if (index === infiniteScrollElementIndex) { return ( <PlaylistItem ref={intersectionTargetRef} key={item.id} playlist={item} /> ); } return <PlaylistItem key={item.id} playlist={item} />; })} {isLoading && <Spinner />} </div> </div> </div> ); } export default Playlists; Although React 19+ and the React Compiler doesn't require the forwardRef it's a handy thing to look into, so for completeness here's my component that uses it (the PlaylistItem)
import { useNavigate } from 'react-router-dom'; import ImagePx from './ImagePx'; import { forwardRef } from 'react'; //forwardRef for use with useIntersection const PlaylistItem = forwardRef(({ playlist }, ref) => { const { name, items: tracks, images, owner, id } = playlist; const navigate = useNavigate(); function handleClick() { navigate(`/playlist/${id}`); } return ( <div className="list-row" role="button" aria-description={`Click to open the playlist called ${name}`} onClick={handleClick} > <div className="col-title" ref={ref}> <ImagePx images={images} size={64} name={name} /> <div className="ellipsis-text-block"> <span className="track-name-font">{name}</span> <br /> {owner?.display_name} </div> </div> <div className="col-playlist-tracks">{tracks.total}</div> </div> ); }); export default PlaylistItem; Let me know your thoughts, I'm still learning so any advice is always most welcome.
Hope that helps :)
