tezvyn:

Re-rendering FlatList on external state change

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

FlatList re-render triggers.

OUTLINE

FlatList is a PureComponent and only checks data and extraData by reference, so pass the external value via extraData and ensure renderItem reads current state.

WHAT THIS TESTS Whether you understand FlatList's prop-based re-render model: it cannot magically know about state it does not receive, and it shallowly compares the props it does receive.

A GOOD ANSWER COVERS FlatList is implemented as a PureComponent, so it skips re-rendering unless one of its tracked props changes by reference, primarily data. State outside data, like a selectedId held in the parent, is invisible to it. The fix is the extraData prop: pass selectedId as extraData so that when it changes to a new value, FlatList knows to re-evaluate its rows. You must also make sure renderItem reads the current selectedId, either through closure over the latest value or by passing it down, otherwise a memoized row may keep stale appearance. If your rows are wrapped in React.memo, the selected flag must be part of the props they compare so the selected row updates while others stay cheap.

COMMON WRONG ANSWERS Mutating the data array in place and reassigning, expecting FlatList to notice, when reference equality fails to detect mutation. Assuming any parent re-render automatically refreshes all rows, ignoring the PureComponent optimization. Putting selectedId only in renderItem's closure but not in extraData, so nothing triggers the update. Recreating the entire data array on every selection just to force a render, which is wasteful.

LIKELY FOLLOW-UPS Why does extraData need a new reference, not a mutated one? How does extraData interact with React.memo on the row? What is the cost of passing a large object as extraData?

ONE CONCRETE EXAMPLE A contact picker tracks selectedId in useState. You render the FlatList with data of contacts and extraData set to selectedId. renderItem reads selectedId to style the chosen row. Tapping a contact calls setSelectedId; because extraData now holds a new value, FlatList re-renders, and the row whose id matches shows the checkmark while the rest, being memoized and unchanged, do not re-render.

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.