React
/Beginner
Lists & Keys
Definition
Keys are special string attributes you must include when creating arrays of elements in React. They help React identify which items have changed, been added, or been removed.
Explain Like I'm New
Imagine you are a teacher keeping track of 30 students in a line. If the line shuffles, you don't want to have to learn everyone's face again. You just look at their Student ID badge (the Key). React uses Keys to instantly know exactly which specific DOM element moved, so it doesn't have to destroy and recreate the entire list from scratch.
Real World Example
When rendering a list of `<TodoItem />` components from a database, you use the unique database ID as the key: `<TodoItem key={todo.id} />`.
Common Use Cases
- •Rendering dynamic lists of data (`.map()`)
- •Forcing a component to completely unmount and remount by changing its key (Key Reset Pattern)
Interactive Example
import React, { useState } from "react"; export default function ListExample() { const [tasks, setTasks] = useState([ { id: "t1", text: "Learn React" }, { id: "t2", text: "Master Keys" }, { id: "t3", text: "Get Hired" } ]); const shuffle = () => { const newTasks = [...tasks].sort(() => Math.random() - 0.5); setTasks(newTasks); }; return ( <div> <button onClick={shuffle}>Shuffle List</button> <ul> {/* GOOD: Using unique IDs. When shuffled, React just moves the DOM nodes. */} {tasks.map(task => ( <li key={task.id}> <input type="checkbox" /> {task.text} </li> ))} </ul> </div> ); }
Interview Questions
basic
- Why does React need a `key` prop in lists?
- What happens if you don't provide a key?
intermediate
- Why is it a bad idea to use the array `index` as a key?
- Where exactly should the key prop be placed in the mapped JSX?
advanced
- How does the Diffing algorithm use keys for O(n) performance?
- Can two different lists on the same page have elements with the same key?
trick
- Does the component itself have access to `props.key`?