What are React keys and why are they important?
React keys help React identify which items in a list are changed, added, or removed. Keys
provide a stable identity for each element, allowing React to optimize re-renders.
- Important: Keys should be unique for each sibling component.
- Why important: Without keys, React has to re-render all list items when the list
changes, which can be inefficient.
Example:
const items = ['apple', 'banana', 'cherry'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);
- Tip: It’s better to use a unique identifier (e.g., id) as a key instead of using index if
the list can change order or content dynamically.