Cơ BảnReact Native iconReact Native

`keyExtractor` trong FlatList quan trọng thế nào?

keyExtractor trả về unique string cho mỗi item, để React reconciler biết phân biệt khi data thay đổi (giống key prop trong list React thường).

tsx
<FlatList
  data={users}
  keyExtractor={(item) => item.id.toString()}
  renderItem={({ item }) => <UserRow user={item} />}
/>

Nếu không cung cấp, FlatList fallback dùng item.key rồi item.id, cuối cùng là index. Dùng index gây bugs nghiêm trọng:
- Xóa item ở giữa → các item sau "shift" key, RN tưởng là item cũ đổi nội dung → state internal (textinput, animation, scroll position con) chuyển nhầm sang item khác.
- Animation transition không match: item mới fade-in trông như item cũ đổi data.

Quy tắc: luôn dùng id thật từ backend, hoặc UUID stable. Đừng dùng Math.random() — mỗi render sinh key mới làm toàn bộ list re-render từ đầu.

Xem toàn bộ React Native cùng filter theo level & chủ đề con.

Mở danh sách React Native