Sub topic 11
Special names: key and ref
This chapter covers two attribute names that look like props but behave differently: key and ref. It assumes you can write function components, pass and destructure props, and use useState. It also assumes you have run a React project, for example one created with Vite. Examples use React 19 and note where React 18 differs.
Two names React reserves
Most attribute names on a component are copied into the props object the child receives. key and ref follow other rules.
keyis read by React during rendering to decide which element is which. It is never delivered to your component as a prop.refis a handle to something React creates, usually a DOM node. In React 19 function components receiverefas an ordinary prop. In React 18 they do not.
The table summarizes the difference.
| Name | Purpose | Readable as `props.x` in the child? | Where it applies |
|---|---|---|---|
| `key` | Identify an element among its siblings | No, in any React version | Any element or component, mainly in lists |
| `ref` | Get a handle to a DOM node or other value | Yes in React 19, no in React 18 | DOM elements and components |
key: identity, not data
When a component re-renders, React compares the new tree to the previous one. For a list of siblings it needs a way to match each new element with an old one. key supplies that match. Elements with the same key at the same position in the tree are treated as the same element, so React keeps their state and DOM nodes and updates them in place.
function TodoItem({ text }) {
return <li>{text}</li>;
}
export default function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<TodoItem key={todo.id} text={todo.text} />
))}
</ul>
);
}The key goes on the element returned inside map, which is the outermost element of each iteration. TodoItem receives text and nothing else.
You cannot read key
If a child needs the identifier, pass it again under a different name.
function Item(props) {
console.log(props.key); // undefined (React warns in development)
return <li>{props.text}</li>;
}
function List({ items }) {
return (
<ul>
{items.map((item) => (
<Item key={item.id} id={item.id} text={item.text} />
))}
</ul>
);
}Here id carries the value into the component. key stays with React.
Rules for good keys
- Keys must be unique among siblings. They do not need to be unique across the whole app, because two different lists can reuse the same values.
- Keys must be stable. A key should come from the data (a database id, a slug, a UUID created when the item was created), not from something recomputed on every render.
- Never generate keys during render with
Math.random()orcrypto.randomUUID(). A new key on every render makes React discard and recreate the element each time. You lose state, focus, and performance. - Use the array index only when the list is static: it is never reordered, filtered, or inserted into.
What goes wrong with index keys
Suppose each row holds an uncontrolled input. With index keys, deleting the first row leaves the keys 0, 1 for what used to be 1, 2. React matches by key, so the first input element is reused for the second item's data. The text you typed into the old first row now appears in the wrong row.
import { useState } from 'react';
function Row({ label }) {
return (
<li>
{label} <input defaultValue="" />
</li>
);
}
export default function BrokenList() {
const [items, setItems] = useState([
{ id: 'a', label: 'Apples' },
{ id: 'b', label: 'Bananas' },
]);
return (
<>
<button onClick={() => setItems(items.slice(1))}>Remove first</button>
<ul>
{items.map((item, index) => (
// Bug: index changes meaning when the list changes.
// Fix: key={item.id}
<Row key={index} label={item.label} />
))}
</ul>
</>
);
}Type something into the "Apples" input, then click "Remove first". The text stays in the first input, which now belongs to "Bananas". Changing the key to item.id fixes it. React then sees that the a element is gone and the b element stays.
Keys on fragments
The short fragment syntax <>...</> cannot take a key. When a list item needs to return several sibling elements, use the named Fragment component.
import { Fragment } from 'react';
function Glossary({ entries }) {
return (
<dl>
{entries.map((entry) => (
<Fragment key={entry.term}>
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
</Fragment>
))}
</dl>
);
}Using key to reset state on purpose
Keys are not only for lists. If you change the key of a component, React treats it as a different element: it unmounts the old one, discarding its state, and mounts a fresh one. This is the standard way to reset a component when an identifying prop changes.
import { useState } from 'react';
function NoteEditor({ userId }) {
const [draft, setDraft] = useState('');
return (
<input
value={draft}
onChange={(e) => setDraft(e.target.value)}
placeholder={`Note for user ${userId}`}
/>
);
}
export default function App() {
const [userId, setUserId] = useState(1);
return (
<>
<button onClick={() => setUserId(userId === 1 ? 2 : 1)}>
Switch user
</button>
<NoteEditor key={userId} userId={userId} />
</>
);
}Without key={userId}, the draft text would carry over when you switch users. With it, each user gets a fresh editor. This is usually simpler and less error-prone than a useEffect that calls setDraft('') when userId changes.
ref: a handle outside the render flow
A ref holds a value that React does not track for rendering. The most common use is reaching a DOM node to call an imperative method such as focus(), scrollIntoView(), or play(). You create a ref with useRef and attach it with the ref attribute.
import { useRef } from 'react';
export default function SearchBox() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} placeholder="Search" />
<button onClick={() => inputRef.current.focus()}>Focus search</button>
</>
);
}React sets inputRef.current to the DOM node after it commits the element to the page, and sets it back to null when the element is removed. Three consequences follow:
- Do not read
ref.currentduring rendering. On the first render it is stillnull. Read it in event handlers and effects. - Changing
ref.currentdoes not cause a re-render. Use state for values that appear in the UI. - Prefer props and state to refs for anything declarative. Refs are an escape hatch for things React cannot express, such as focus, scrolling, measuring, and third-party DOM libraries.
Passing ref to your own component
In React 19, ref is a normal prop for function components. Accept it in the parameter list and hand it to the DOM element inside.
import { useRef } from 'react';
function TextInput({ label, ref, ...rest }) {
return (
<label>
{label}
<input ref={ref} {...rest} />
</label>
);
}
export default function SignupForm() {
const nameRef = useRef(null);
return (
<form>
<TextInput label="Name" ref={nameRef} />
<button type="button" onClick={() => nameRef.current.focus()}>
Focus name
</button>
</form>
);
}The parent holds the ref, the child decides which inner element it points to. This also shows why the rest pattern from the spread chapter works here: ref is pulled out of rest on purpose, so it is attached explicitly.
React 18: forwardRef
In React 18 and earlier, ref is not included in props. Passing ref to a function component gives you null in the ref and a console warning. You must wrap the component in forwardRef, which gives it a second argument.
import { forwardRef } from 'react';
const TextInput = forwardRef(function TextInput({ label, ...rest }, ref) {
return (
<label>
{label}
<input ref={ref} {...rest} />
</label>
);
});React 19 still accepts forwardRef, but plain ref props are the recommended style for new code. Check your installed version before choosing.
Limiting what a parent can reach
Forwarding a ref to a raw DOM node gives the parent full access to that node. If you want to expose only a few operations, use useImperativeHandle inside the child to publish a small object instead. Use it sparingly. It is rarely needed.
Callback refs
The ref attribute also accepts a function. React calls it with the node when the element mounts. Since React 19 the function may return a cleanup function, which React calls when the element unmounts.
function MeasuredBox({ children }) {
return (
<div
ref={(node) => {
if (node) console.log('Height:', node.getBoundingClientRect().height);
}}
>
{children}
</div>
);
}An inline function like this is a new function on every render, so React calls it again each time. That is fine for logging but wasteful for expensive work. Define a stable function with useCallback in that case.
Common errors
- Reading
props.keyorprops.refand gettingundefinedin React 18. Pass the value under another name. - Putting
keyon the wrong element, such as on an inner<li>while the outer component returned frommaphas none. React warns that each child in a list needs a unique key. - Using
key={index}on a list that can be reordered or filtered. Symptoms are inputs that keep the wrong text and animations that run on the wrong row. - Passing
refto a function component in React 18 withoutforwardRef. - Reading
ref.currentduring render and gettingnull. - Using a changing key by accident, for example
key={Math.random()}. The component remounts on every render and loses focus and state.
Exercise
A list renders items.map((item, i) => <Row key={i} item={item} />). Users can sort the list, and each Row contains an uncontrolled text input. After sorting, typed text appears next to the wrong items. Why does this happen, and what is the fix?
Show answer
With index keys, React matches elements by position. After sorting, the element at index 0 is reused for whichever item is now first, and its input keeps its old DOM state. The fix is to use a stable identifier from the data, such as key={item.id}, so each input stays attached to its item when the order changes.
Exercise
You are on React 19 and write function Field({ label, ...rest }) { return <input {...rest} />; }. A parent renders <Field label="Age" ref={ageRef} />. Does ageRef.current point to the input? What do you change?
Show answer
Yes. In React 19 ref is a normal prop, so it is collected in rest and spread onto the <input>, which attaches it. Making this explicit is clearer: destructure ref and write <input ref={ref} {...rest} />. In React 18 the ref would stay null because ref is not in props, and you would need forwardRef.
Exercise
A ProfileForm component keeps draft text in state. When the parent switches from user 1 to user 2, the old draft is still shown. How can you reset it without an effect?
Show answer
Give the component a key based on the user, for example <ProfileForm key={userId} userId={userId} />. When the key changes, React unmounts the old instance and mounts a new one with fresh state.