tezvyn:

Implementing infinite scroll with FlatList

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

pagination with FlatList.

OUTLINE

use onEndReached with onEndReachedThreshold to fetch the next page, append results, and show a footer loader; guard with a loading flag to prevent duplicate fetches.

WHAT THIS TESTS Whether you can wire FlatList pagination correctly and anticipate the well-known pitfall where onEndReached fires multiple times and loads pages repeatedly.

A GOOD ANSWER COVERS Use the onEndReached callback, which fires when the user scrolls within onEndReachedThreshold of the list's end; the threshold is expressed in units of visible length, so a value like 0.5 triggers half a screen from the bottom. In the handler, fetch the next page using a tracked page or cursor, then append the results to the existing data array rather than overwriting it. Show progress with ListFooterComponent rendering a spinner while fetching. The essential guard is a loading flag: bail out of onEndReached if a request is already in flight, and also stop once the server indicates there are no more pages, so you do not hammer the API. Reset state for pull-to-refresh.

COMMON WRONG ANSWERS Omitting the in-flight guard, so onEndReached fires several times during a fling and launches overlapping requests, producing duplicate or out-of-order items. Replacing data instead of appending, which discards earlier pages. Forgetting to stop at the last page, looping requests forever. Setting onEndReachedThreshold too high, triggering loads far too early. Not handling errors, leaving a perpetual spinner.

LIKELY FOLLOW-UPS Why might onEndReached fire on initial mount with little data, and how do you prevent it? How does this differ with a library like React Query's infinite queries? How do you dedupe items if the backend returns overlaps?

ONE CONCRETE EXAMPLE A feed keeps items, page, isLoading, and hasMore in state. onEndReachedThreshold is 0.5. loadMore checks if isLoading or not hasMore and returns early; otherwise it sets isLoading true, fetches page plus one, appends the results, increments page, sets hasMore from the response, and clears isLoading. ListFooterComponent shows a spinner while isLoading. The guard ensures a fast scroll to the bottom triggers exactly one request, not five, and the list grows page by page until the server reports no more results.

Read the original → reactnative.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.