Course contentsShow
← React Native
Lesson 334 of 1,5554. Flexbox and Native StylingFree lesson

Handling Heavy Media Layouts

Structure layouts to lazy-load expensive visual components only when they enter the viewport.

In this lesson, you will learn how to improve your app's responsiveness by lazily rendering media-heavy components only when they are about to enter the user's viewport.

The Problem: Loading Everything at Once

When building a feed or a gallery, developers often try to render all components simultaneously. If your feed contains high-resolution images, videos, or complex interactive components, React Native has to calculate the layout and load all those assets into memory immediately. This causes the UI thread to stutter, leading to dropped frames and a sluggish scrolling experience—a phenomenon closely related to the "Layout Thrashing" we discussed earlier.

The Solution: Viewport-Aware Rendering

To fix this, we implement a strategy where we only render the heavy component when it is visible (or very close to being visible). Instead of rendering a Video or a HighResImage component directly, we render a lightweight "placeholder" component.

We then monitor the scroll position. When the placeholder enters the viewport, we swap it for the actual heavy media component.

Practical Implementation

You can achieve this by leveraging the onViewableItemsChanged prop provided by list components like FlatList.

const renderItem = ({ item }) => {
  // If the item is in the "visibleItems" state, render the heavy media
  // Otherwise, render a low-weight placeholder view
  return isVisible(item.id) ? (
    <HeavyVideoPlayer source={item.url} />
  ) : (
    <View style={styles.placeholder} />
  );
};

<FlatList
  data={mediaList}
  renderItem={renderItem}
  onViewableItemsChanged={handleViewableItemsChange}
  viewabilityConfig={{ itemVisiblePercentThreshold: 50 }}
/>

In this example, the HeavyVideoPlayer is only injected into the component tree when it meets the 50% visibility threshold. This minimizes the initial memory footprint and prevents the layout thread from being overwhelmed by expensive tasks for items the user hasn't scrolled to yet. By keeping your component tree shallow and only initializing heavy resources on demand, you ensure that even media-rich layouts remain silky smooth.

Key Takeaway: To keep layouts fluid, avoid rendering heavy media components until they are actually visible to the user, effectively offloading the initial memory and processing burden.