Rendering lists is common in React, but small mistakes can cause bugs or slow apps. Knowing these mistakes helps you write better code.
0
0
Common list rendering mistakes in React
Introduction
When showing a list of items like tasks, messages, or products
When updating a list dynamically based on user actions
When rendering lists with React components inside
When optimizing performance for large lists
When debugging unexpected UI behavior in lists
Syntax
React
function ListComponent({ items }) { return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }
Always add a unique key prop to each list item to help React track changes.
Keys should be stable and unique, not just array indexes.
Examples
Correct: Each item has a unique
id used as the key.React
const items = [{ id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }]; function FruitList() { return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }
Using index as key can cause problems if list changes order or items are added/removed.
React
const items = ['Apple', 'Banana']; function FruitList() { return ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> ); }
Missing
key prop causes React warnings and can lead to rendering bugs.React
const items = ['Apple', 'Banana']; function FruitList() { return ( <ul> {items.map(item => ( <li key={item}>{item}</li> // Missing key prop fixed by adding key ))} </ul> ); }
Duplicate keys cause React to confuse items and update wrong elements.
React
const items = [{ id: 1, name: 'Apple' }, { id: 1, name: 'Banana' }]; function FruitList() { return ( <ul> {items.map(item => ( <li key={item.id}>{item.name}</li> ))} </ul> ); }
Sample Program
This React component shows a list of fruits with unique keys. Clicking the button adds a new fruit with a unique id. This avoids common mistakes like missing keys or duplicate keys.
React
import React, { useState } from 'react'; function FruitList() { const [fruits, setFruits] = useState([ { id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' } ]); function addFruit() { // Adding a new fruit with a unique id const newFruit = { id: fruits.length + 1, name: 'Date' }; setFruits([...fruits, newFruit]); } return ( <div> <button onClick={addFruit} aria-label="Add fruit">Add Fruit</button> <ul> {fruits.map(fruit => ( <li key={fruit.id}>{fruit.name}</li> ))} </ul> </div> ); } export default FruitList;
OutputSuccess
Important Notes
Using array index as key is okay only if the list never changes order or items.
Keys help React update only changed items, improving performance.
Common mistake: forgetting keys or using non-unique keys causes UI bugs and warnings.
Summary
Always add a unique and stable key prop when rendering lists.
Avoid using array indexes as keys if the list can change.
Proper keys help React update the UI efficiently and correctly.