tezvyn:

VirtualizedList: The Engine Behind React Native Lists

AI-drafted, machine-checkedSource: reactnative.devadvanced

VirtualizedList is the engine behind React Native's efficient lists, rendering only visible items to save memory. Use it when FlatList isn't flexible enough, like for immutable data. The main footgun: component state is lost when items scroll out of view.

WHY IT EXISTS Rendering a list with thousands of items by creating a component for every single one would crash most apps due to excessive memory usage and slow performance. VirtualizedList solves this by only rendering what's necessary for a smooth user experience, making long lists feasible on mobile devices.

THE MENTAL MODEL Think of VirtualizedList as a film projector. The projector only illuminates a single frame at a time (the "render window"), even though the entire film reel (your data) exists. As you scroll, new frames are brought into the light and old ones return to darkness. This saves the "energy" (memory and CPU) of rendering everything at once.

HOW IT WORKS VirtualizedList maintains a finite render window of items. It renders components for items inside this window and replaces everything outside with blank views of the appropriate size to keep the scrollbar accurate. Unlike FlatList, which assumes a simple array, VirtualizedList is generic. You must provide it with getItem and getItemCount functions to tell it how to access an item at a given index and how many items exist. This allows it to work with any data structure, like an immutable list or paged API data.

WHEN TO USE IT Use VirtualizedList directly when FlatList or SectionList are too restrictive. The primary use case is when your data is not a simple array. For example, if you're using a library like Immutable.js, you can provide custom getItem and getItemCount functions to interface with your data structure. It offers maximum flexibility at the cost of more boilerplate code.

WHEN NOT TO USE IT For most common cases, prefer FlatList or SectionList. These components are convenience wrappers around VirtualizedList that are optimized for simple arrays and are much easier to use. If your data is in an array, using VirtualizedList directly is just reinventing the functionality that FlatList already provides.

ONE CANONICAL EXAMPLE A common footgun is UI not updating. VirtualizedList is a PureComponent, meaning it only re-renders if its props change. If your renderItem function depends on parent state that isn't passed as a prop, your items won't update. To fix this, pass any external dependencies into the extraData prop. When extraData changes, the list knows it needs to re-render its items. For example, if a selectedItemId state in the parent component affects item styling, you must pass extraData={selectedItemId} to the list.

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.