Tutorials Logic, IN info@tutorialslogic.com

React Lists Keys map key Prop

Rendering Lists in React

React often needs to display repeated data such as products, users, comments, menu items, or notifications. Rendering lists means taking an array of data and turning each item into JSX using map().

Basic List Example

Basic List Example - JSX Example

Basic List Example - JSX Example
const fruits = ['Apple', 'Banana', 'Orange']

function FruitList() {
    return (
        <ul>
            {fruits.map(fruit => <li key={fruit}>{fruit}</li>)}
        </ul>
    )
}

What Are Keys?

Keys are special values React uses to identify which list items changed, were added, or were removed. They help React update lists efficiently and correctly. A key should be stable and unique among siblings.

List of Objects

List of Objects - JSX Example

List of Objects - JSX Example
const users = [
    { id: 1, name: 'Aman' },
    { id: 2, name: 'Riya' },
]

function UserList() {
    return (
        <ul>
            {users.map(user => (
                <li key={user.id}>{user.name}</li>
            ))}
        </ul>
    )
}

Nested Lists

Nested Lists - JSX Example

Nested Lists - JSX Example
const categories = [
    { id: 1, title: 'Frontend', topics: ['HTML', 'CSS', 'React'] },
    { id: 2, title: 'Backend', topics: ['Node.js', 'Express'] },
]

function CategoryList() {
    return (
        <div>
            {categories.map(category => (
                <div key={category.id}>
                    <h3>{category.title}</h3>
                    <ul>
                        {category.topics.map(topic => (
                            <li key={topic}>{topic}</li>
                        ))}
                    </ul>
                </div>
            ))}
        </div>
    )
}

Dynamic List Example

Dynamic List Example - JSX Example

Dynamic List Example - JSX Example
import { useState } from 'react'

function TodoList() {
    const [todos, setTodos] = useState([
        { id: 1, text: 'Learn React' },
        { id: 2, text: 'Practice hooks' },
    ])

    function removeTodo(id) {
        setTodos(current => current.filter(todo => todo.id !== id))
    }

    return (
        <ul>
            {todos.map(todo => (
                <li key={todo.id}>
                    {todo.text}
                    <button onClick={() => removeTodo(todo.id)}>Remove</button>
                </li>
            ))}
        </ul>
    )
}

Why Stable Keys Matter

Stable keys help React match the correct item between renders. If the wrong key is used, React may reuse the wrong DOM element or component instance, which can cause visual bugs or incorrect input behavior.

Best Practices for Keys

  • Use unique stable IDs when available
  • Avoid array indexes as keys when list order can change
  • Keep keys on the outermost rendered element inside map()
  • Keys only need to be unique among siblings, not globally

List Rendering Failure Cases

Mistake Why it is risky Better approach
Using array indexes as keys in reordering lists Can cause wrong items to keep wrong state Use a stable unique ID
Forgetting the key entirely Causes React warnings and weak diffing Add a unique key in each mapped element
Using non-unique keys Can confuse React updates Choose keys that are unique among siblings

Summary

Lists are a common part of React applications, and map() is the usual way to render them. Keys are essential because they help React track which items changed between renders. Once you understand lists and keys well, you can build dynamic collections much more reliably.

Keys Preserve Identity During Reconciliation

A key tells React which previous child corresponds to each child in the next render. When an item moves, a stable domain identifier lets React move its component instance and local state with it. An array index describes a position instead; inserting, sorting, or filtering can then attach an input value, focus state, or animation to the wrong record.

Keys need to be unique only among siblings, but they must remain stable for the lifetime of that record. Generate an identifier when the data is created, not during render. The key is consumed by React and is not passed as a normal prop, so pass the identifier separately when the child needs it.

  • Use a database or domain identifier when one exists.
  • A composite key is acceptable only when its components are stable and unambiguous.
  • Changing a key intentionally resets the component and all state below it.

Render Empty, Loading, Error, and Large Collections Deliberately

A list screen needs defined behavior before data arrives, when the request fails, when no records match, and when more data is loading. Keep those states separate so an empty result is not mistaken for a network failure. Cancel or ignore stale requests when filters change quickly, and preserve the active selection only while its record still exists.

Thousands of mounted rows can make rendering, layout, and interaction slow even when map itself is simple. Paginate, window, or virtualize after measuring. A virtualized row still needs a stable item key, predictable height behavior, keyboard navigation, and an accessible announcement strategy for content outside the mounted window.

Nested Lists Need Local Keys and Valid Markup

Each map call creates its own sibling set and therefore its own key requirement. Put the key on the element returned directly from that map, including a Fragment when the item returns multiple siblings. A key hidden inside the child component cannot identify that child to the parent list.

Use ul or ol with li for semantic lists and table markup for tabular rows. Interactive rows need real buttons or links, visible focus, and event handling that does not make nested controls trigger the row action accidentally. Test duplicate labels, reordered groups, deletion of the focused row, and server updates arriving in a different order.

Before you move on

React Lists Keys map key Prop Mastery Check

5 checks
  • React often needs to display repeated data such as products, users, comments, menu items, or notifications.
  • Rendering lists means taking an array of data and turning each item into JSX using map().
  • Keys are special values React uses to identify which list items changed, were added, or were removed.
  • They help React update lists efficiently and correctly.
  • A key should be stable and unique among siblings.
Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.