Keys in React
Ключи в React
A React key tells React which list item is which across renders. When items move, stable keys help keep each component’s local state with the right item rather than with its old position.
Also known as: key prop
What problem do keys solve?
Imagine a contact list with an editable nickname in each row. You start editing Mia’s nickname, then sort the list. The draft should follow Mia, not stay in the third row. A key lets React recognize Mia’s row even when it appears in a different position.
How React matches children
During reconciliation, React compares the previous and next sets of children. Within the same parent, a child with the same key and element type can keep its component state even if it moves. Without explicit keys, React falls back to position, which can make one item inherit another item’s state.
Keys need to be unique among siblings, not across the whole app. They should also be stable: use the same key for the same record on each render. A key preserves identity; it does not prevent a component from rendering again or guarantee that its DOM stays unchanged.
Example: render a contact list
function ContactList({ contacts }) {
return (
<ul>
{contacts.map(contact => (
<ContactRow key={contact.id} contact={contact} />
))}
</ul>
);
}
Put the key on ContactRow, the element returned by map, not on the <li> that ContactRow might render internally. React uses key itself and does not pass it through as props.key. If the row needs the ID, it can read contact.id or receive a separate prop.
Common mistakes
- Using the array index for a changing list. If you insert a contact at the top, the new row gets index
0. React can reuse the previous first row’s state for the new contact. An index is fine for a fixed list whose items never shift or get replaced by different records. - Generating a new key during every render. A random key makes React treat the row as new, discarding local state and potentially losing input focus. If a record has no ID yet, generate one when you create the record and store it with the data.
Interview question: can a key reset state?
Yes. A key is useful even without a list. For example, <MessageComposer key={recipientId} /> makes React unmount the old composer and mount a fresh one when the recipient changes. That clears the composer’s local draft rather than carrying it into a different conversation. By contrast, updating an ordinary prop does not by itself reset local state.