Course contentsShow
← React Native
Lesson 201 of 1,5553. Core Primitive ComponentsFree lesson

Managing List Item Item Visibility

Learners will trigger side effects based on which elements are currently on screen.

In this lesson, you will learn how to trigger logic based on which specific items are currently visible on the screen as a user scrolls through a list.

Understanding Visibility Tracking

When working with long lists in React Native, it is often useful to know exactly what the user is looking at. For example, you might want to automatically play a video when it enters the viewport, pause it when it leaves, or trigger an analytics event when an item is fully displayed.

React Native provides a built-in property within the FlatList component called onViewableItemsChanged. This acts as a "listener" that informs your code whenever the list items currently in the user's view change.

Using onViewableItemsChanged

To use this, you need to provide a callback function and a configuration object called viewabilityConfig. The viewabilityConfig is crucial because it defines what "visible" actually means to your app (e.g., does an item count as visible if only 10% of it is showing, or does it need to be 50%?).

Here is a simplified example of how you might set this up:

const onViewableItemsChanged = ({ viewableItems }) => {
  viewableItems.forEach((item) => {
    console.log("Visible item ID:", item.key);
  });
};

const viewabilityConfig = {
  itemVisiblePercentThreshold: 50, // Triggers when 50% of the item is visible
};

<FlatList
  data={myListData}
  renderItem={renderItem}
  onViewableItemsChanged={onViewableItemsChanged}
  viewabilityConfig={viewabilityConfig}
/>

Why This Matters

By using onViewableItemsChanged, you can keep your app performance high and user experience smooth. Instead of running heavy logic on every single item in your list, you only execute side effects for the items that the user is actively interacting with. This is the foundation for creating dynamic, reactive interfaces where the content "knows" when it is in the spotlight.

Key Takeaway: Use onViewableItemsChanged paired with a viewabilityConfig to trigger specific actions precisely when an item enters or exits the user’s view.