keyExtractor
- React Native course
- Beginner
- Lesson 55/116
- 5 min
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.
Practice 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} />.
Starter code
import React from 'react';
import { FlatList, Text } from 'react-native';
export default function UserList() {
const users = [
{ id: 'u1', name: 'Alex' },
{ id: 'u2', name: 'Sam' }
];
// Add a FlatList
return null;
}Sample 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}
/>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each key type to its behavior
| Term | Meaning |
|---|---|
item.id |
Key by unique id |
index.toString() |
Key by index |
keyExtractor |
Function producing keys |
unique key |
Enables item tracking |
2 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 Correct answer
- The app crashes
- Nothing happens
Explanation: A default string key is used but a warning appears in the console.
3 Write the keyExtractor body
keyExtractor={(item) =>____}
keyExtractor={(item) =>item.id}
Explanation: item.id is unique per item.