Lists and Keys
You’ll often need to display multiple similar components from a collection of data. In React, you can use JavaScript array methods to render lists of components.Rendering Arrays with map()
Use themap() method to transform an array of data into an array of JSX elements:
Rendering Array of Objects
Most commonly, you’ll map over an array of objects:The Key Prop
Every item in a list needs akey prop - a unique string or number that identifies it among siblings:
Why keys matter: Keys help React identify which items have changed, been added, or been removed. Without proper keys, React may re-render items incorrectly or lose component state.
What Happens Without Keys
Where to Get Keys
When NOT to use index as key:
- Items can be reordered (sorting, filtering)
- Items can be added or removed
- The list can be paginated or filtered
- Items have state (like input fields)
Rules for Keys
Keys Must Be Unique Among Siblings
Keys Must Not Change
Keys Are Not Passed to Components
Filtering Lists
Filter arrays before mapping:Sorting Lists
Sort arrays before mapping (don’t mutate original):Nested Lists
Each level of nesting needs its own keys:Extracting Components from Lists
Extract list items into separate components for better organization:Complete Shopping List Example
Performance Considerations
For large lists, consider these optimizations:For very large lists (1000+ items):
- Consider virtualization libraries (react-window, react-virtualized)
- Implement pagination or infinite scroll
- Use
useMemofor expensive filtering/sorting - Lazy load data as needed
Best Practices
Key principles for lists:
- Always provide a
keyprop when rendering lists - Use unique, stable identifiers (database IDs are ideal)
- Avoid using array index as key unless the list is truly static
- Extract list items into separate components
- Filter and sort data before mapping
- Keep keys unique among siblings
- Don’t generate random keys on each render