React Native
keyExtractor
Learn unique keys with keyExtractor.
keyExtractor
keyExtractor gives each item a unique key. React Native uses these keys to track items; when the list updates, it tells which item was added, removed or moved by these keys. The function takes an item and returns a string.
Example: keyExtractor={(item) => item.id}. Here item.id is unique per task and used as the key. If there is no unique id field, you can use (item, index) => index.toString(); but this pattern can break when the list order changes, so id is preferred.
Keys from id
The most robust key is item.id. Most items coming from a data source already have a unique id field: database records, API responses, users, tasks. Writing keyExtractor={(item) => item.id} is enough.
The index approach (item, index) => index.toString() is acceptable only for a static list. When the list is sorted, filtered or has items added, the indexes change; React Native may update the wrong items. So use id whenever possible. Generating a unique value like Date.now().toString() also works.
Exercise Write a list keyed by id
Complete the empty component. The users array is defined: each object has id and name fields. Return <FlatList data={users} renderItem={({ item }) => <Text>{item.name}</Text>} keyExtractor={(item) => item.id} />.
Show example solution
import React from 'react';
import { FlatList, Text } from 'react-native';
export default function UserList() {
const users = [
{ id: 'u1', name: 'Alex' },
{ id: 'u2', name: 'Sam' }
];
return (
<FlatList
data={users}
renderItem={({ item }) => <Text>{item.name}</Text>}
keyExtractor={(item) => item.id}
/>
);
}
Test yourself
-
Match each key type to its behavior
- item.id
- Key by unique id
- index.toString()
- Key by index
- keyExtractor
- Function producing keys
- unique key
- Enables item tracking
-
What happens if keyExtractor is not provided?
<FlatList
data={tasks}
renderItem={...}
/>
- The list does not work
- A default string key is used but a warning is shown
- The app crashes
- Nothing happens
Show answer
A default string key is used but a warning is shown — A default string key is used but a warning appears in the console.
-
Write the keyExtractor body
keyExtractor={(item) =>____}
Show answer
keyExtractor={(item) =>item.id}
Next lesson: SectionList