tezvyn:

React Native: Infinite Scroll with onEndReached

AI-drafted, machine-checkedSource: archive.reactnative.devintermediate

The `onEndReached` prop is a callback that fires when you scroll near a list's end, letting you fetch more data. Use it in `FlatList` for feeds or catalogs. The main footgun: it can fire multiple times, so use a loading flag to prevent redundant API.

WHY IT EXISTS: Mobile apps often display lists with thousands of items. Loading all this data at once would consume huge amounts of memory and make the app slow to start. Infinite scrolling provides a better user experience by loading just enough data to fill the screen, then fetching more as the user scrolls down.

THE MENTAL MODEL: Think of onEndReached as a sensor placed near the bottom of your list. When the last rendered item gets within a certain distance of the end of the viewport, this sensor fires a function you provide. Your function is responsible for fetching the next "page" of data from your API and appending it to the list's data source.

HOW IT WORKS: You pass a function to the onEndReached prop of a FlatList or SectionList. This function typically sets a loading state to true, makes an API call for the next page of data, and once the data arrives, appends it to the existing data array in your component's state. The onEndReachedThreshold prop, a number between 0 and 1, determines how close to the end (as a fraction of the list's visible length) the user must be for the callback to fire. A value of 0.5 means it triggers when the end of the content is within half the visible length of the list.

WHEN TO USE IT: Use onEndReached for any list where the dataset is too large to load at once. This is standard for social media feeds, product listings in an e-commerce app, search results, or long message histories. It's a core pattern for building performant, scalable lists in React Native.

WHEN NOT TO USE IT: Don't use it for short, finite lists where all data can be loaded upfront without a performance penalty, like a settings menu. If your list items have vastly different, unpredictable heights and performance is suffering, you might need a more complex virtualization strategy, though FlatList handles most cases well.

ONE CANONICAL EXAMPLE: A common mistake is failing to prevent multiple fetches. The onEndReached callback can fire rapidly if the user scrolls near the end. To fix this, use a loading flag. Inside your onEndReached function, first check if a fetch is already in progress (e.g., if (loading) return;). If not, set loading to true, make your API call, and only set loading back to false after the new data has been successfully added to your state. This ensures you only fetch one page of data at a time.

Read the original → archive.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.