tezvyn:

Optimizing FlatList with variable item heights

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

layout optimization for mixed heights.

OUTLINE

implement getItemLayout to return each item's length and cumulative offset so FlatList skips measurement and scrollToIndex works precisely; precompute heights per item type.

WHAT THIS TESTS Whether you understand that FlatList performs best when it does not have to measure items at runtime, and how to provide layout for items whose heights vary but are computable.

A GOOD ANSWER COVERS The key tool is getItemLayout, which returns the length, offset, and index for a given position. Normally it is trivial for fixed-height rows, but with mixed content like text bubbles and image bubbles you must compute each item's height from its type and content, then accumulate offsets. To keep getItemLayout fast, precompute a running array of offsets when data changes so each call is a constant-time lookup rather than summing every prior item. Providing accurate layout lets FlatList skip synchronous measurement, which cuts blank cells during fast scrolling and, critically, makes scrollToIndex land precisely because FlatList knows the exact pixel offset of the target. If some heights are genuinely unpredictable, handle onScrollToIndexFailed to recover gracefully.

COMMON WRONG ANSWERS Returning a single constant height for items that actually vary, which corrupts every offset after the first variable item and makes scrollToIndex jump to the wrong place. Recomputing the full offset sum inside getItemLayout on every call, making it O(n) per item and slow for long lists. Omitting getItemLayout and then complaining scrollToIndex is unreliable. Measuring with onLayout and storing heights but never feeding them back to getItemLayout.

LIKELY FOLLOW-UPS Why does scrollToIndex misbehave without getItemLayout for off-screen items? How do you handle onScrollToIndexFailed? When is FlashList's automatic sizing a better fit than manual getItemLayout?

ONE CONCRETE EXAMPLE In a chat list, text messages are 60px and image messages are 220px. When messages change you build an offsets array by scanning once and summing per-type heights. getItemLayout for index i returns length from the item's type, offset from offsets[i], and index i, all O(1). Now scrolling is smooth with few blanks, and scrollToIndex to the latest message jumps exactly to its true offset instead of an estimate, even though earlier items have different heights.

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.