Lists and Keys in React

πŸ“˜ React.js πŸ‘ 43 views πŸ“… Nov 05, 2025
⏱ Estimated reading time: 2 min

In React, lists are used to display multiple items, and keys help React identify which items have changed, been added, or removed.


Rendering Lists

Use JavaScript’s map() function to render lists.

function NumberList() { const numbers = [1, 2, 3, 4]; return ( <ul> {numbers.map(num => ( <li>{num}</li> ))} </ul> ); }

Why Keys Are Important

Keys help React:

  • Track list items efficiently

  • Improve performance

  • Prevent unnecessary re-renders

Without keys, React shows a warning.


Adding Keys

Each list item must have a unique key.

function NumberList() { const numbers = [1, 2, 3, 4]; return ( <ul> {numbers.map(num => ( <li key={num}>{num}</li> ))} </ul> ); }

Using Objects in Lists

function Users() { const users = [ { id: 1, name: "Alice" }, { id: 2, name: "Bob" } ]; return ( <ul> {users.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }

Rules for Keys

βœ… Keys should be:

  • Unique among siblings

  • Stable (do not change)

❌ Avoid:

  • Using array index as key (if list can change)

  • Item</li> // not recommended

  • When Index as Key Is Acceptable

    • Static lists

    • Items never change order

    • No items added or removed


    Keys Are Not Props

    • Keys are used internally by React

    • They are not accessible inside the component


    Conditional Rendering with Lists

    {items.length > 0 ? ( items.map(item => <Item key={item.id} {...item} />) ) : ( <p>No items available</p> )}

    Best Practices

    • Always use a unique ID as key

    • Avoid random values (Math.random())

    • Keep list rendering simple


    Key Points

    • Use map() to render lists

    • Keys help React track changes

    • Unique and stable keys are essential

    • Avoid using index as key when possible


    πŸ”’ Some advanced sections are available for Registered Members
    Register Now

    Share this Post


    ← Back to Tutorials

    Popular Competitive Exam Quizzes