Sub topic 11
Special names: key and ref
This chapter assumes you can write function components, destructure props, and render a list with map. It also assumes you know what useState and useRef do at a basic level.
Most attribute names on a component become props. Two names do not: key and ref. React treats them specially, and this changes how you read them in the child.
key is for React, not for your component
key tells React which item in a list is which between renders. React uses it to match old elements to new ones, so it can keep, move, or remove the right DOM nodes and component state.
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}React does not pass key to the component. If a child reads props.key, it gets undefined, and React logs a warning in development. If the child needs the value, pass it again under another name, such as id={todo.id}.
Rules for good keys
- Keys must be unique among siblings, not across the whole app.
- Keys must be stable. Use an ID from your data, not
Math.random(), which creates a new identity on every render and destroys each item's state. - Avoid array indexes when items can be reordered, inserted, or removed. State then stays attached to the position instead of the item.
Using key to reset state
A key works outside lists too. When the key on a component changes, React discards the old instance and mounts a new one, so its state starts fresh.
function ProfilePage({ userId }) {
return <Profile key={userId} userId={userId} />;
}Without the key, switching userId would keep the same Profile instance and any state inside it, such as a half-typed comment. With the key, each user gets a clean component.
ref gives access to a DOM node
ref holds a reference to something React created, most often a DOM element. You normally create it with useRef and read it through .current.
In React 19, ref is an ordinary prop for function components. You can destructure it and pass it on to an element.
import { useRef } from 'react';
function TextInput({ ref, label, ...rest }) {
return (
<label>
{label}
<input ref={ref} {...rest} />
</label>
);
}
export default function Form() {
const inputRef = useRef(null);
return (
<>
<TextInput ref={inputRef} label="Name" />
<button onClick={() => inputRef.current.focus()}>Focus the field</button>
</>
);
}The parent owns inputRef. The child decides which element receives it. After the first render, inputRef.current is the <input> DOM node.
Comparing the two
| Name | Delivered to the child as a prop? | Purpose |
|---|---|---|
| `key` | No, in any version | Identify an element among siblings, or reset a component |
| `ref` | Yes in React 19, no in React 18 | Reach a DOM node or other instance |
Common errors
- Reading
props.key. It is alwaysundefined. Pass the value under a different name. - Missing keys in a list. React warns, and falls back to using indexes.
- Putting the key on the wrong element. The key belongs on the outermost element returned from
map, not on a child inside the component. - Reading
ref.currentduring render. It isnulluntil after the first commit. Read it in event handlers or effects. - Using a spread without noticing
ref. In React 19,{...rest}forwardsreftoo if you did not destructure it, which is often what you want.
Exercise
A Chat component keeps the draft message in state. When the user selects a different contact, the old contact's draft still appears. The component is rendered as <Chat contactId={contactId} />. What one-line change fixes it, and why does it work?
Show answer
Render <Chat key={contactId} contactId={contactId} />. When the key changes, React unmounts the old Chat instance and mounts a new one, so its state, including the draft, starts empty.