Sub topic 16
State identity, position, and resetting with key
This chapter assumes you can write function components, pass props, and use useState with event handlers. It also assumes you know that each render gives a component a fixed snapshot of its state. Here you will learn how React decides which state belongs to which component, and how to use the key attribute to reset that state on purpose.
State belongs to a position in the tree
A component does not store its state inside the function. React stores it, and ties it to the component's position in the render tree. When a parent re-renders, React compares the new tree to the previous one. If a component of the same type sits in the same position, React keeps its state. If the type or position changes, React discards the old component and its state, and mounts a new one with fresh initial state.
This explains a common surprise. State is not tied to the JSX you wrote. It is tied to what React finds at each spot after rendering.
import { useState } from 'react';
function Counter({ label }) {
const [score, setScore] = useState(0);
return (
<button onClick={() => setScore(score + 1)}>
{label}: {score}
</button>
);
}
function App() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<>
{isPlayerA ? <Counter label="Player A" /> : <Counter label="Player B" />}
<button onClick={() => setIsPlayerA(!isPlayerA)}>Switch player</button>
</>
);
}Click the counter a few times, then click "Switch player". The label changes to "Player B", but the score stays. Both branches render a Counter at the same position, so React treats them as the same component receiving new props. Only label changed.
When state is reset automatically
React resets state when the component at a position changes type, or when the component disappears from the tree.
- Rendering
<Counter />in one branch and<p>in another resets the counter when you switch. - Rendering
nullinstead of<Counter />unmounts it, so its state is lost. - Rendering the same component conditionally and then showing it again starts it from its initial state.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
function App() {
const [show, setShow] = useState(true);
return (
<>
{show && <Counter />}
<button onClick={() => setShow(!show)}>
{show ? 'Hide' : 'Show'} counter
</button>
</>
);
}Hide the counter and show it again. It starts at 0, because hiding it unmounted it.
Same position, different children
Sometimes you want state to reset when the component at a position stays the same type, but represents something different. The first example above is the case. If two players should have separate scores, you have two options.
- Render each in a different position.
- Give each a distinct
key.
The first option looks like this:
import { useState } from 'react';
function Counter({ label }) {
const [score, setScore] = useState(0);
return (
<button onClick={() => setScore(score + 1)}>
{label}: {score}
</button>
);
}
function App() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<>
{isPlayerA && <Counter label="Player A" />}
{!isPlayerA && <Counter label="Player B" />}
<button onClick={() => setIsPlayerA(!isPlayerA)}>Switch player</button>
</>
);
}Each Counter now occupies its own slot in the parent's children. When isPlayerA is true, the second slot holds false, which renders nothing. Switching unmounts one and mounts the other, so scores reset every time you switch.
Resetting state with a key
A key tells React which element is which. You already use keys in lists. They also work outside lists. If the key changes between renders, React treats the element as a different component, even when the type and position are the same.
This is the most direct way to reset a component's state:
import { useState } from 'react';
function Profile({ userId }) {
const [draft, setDraft] = useState('');
return (
<input
value={draft}
onChange={e => setDraft(e.target.value)}
placeholder={`Note for user ${userId}`}
/>
);
}
function App() {
const [userId, setUserId] = useState(1);
return (
<>
<button onClick={() => setUserId(userId + 1)}>Next user</button>
<Profile key={userId} userId={userId} />
</>
);
}Type something into the input, then click "Next user". The key changes from 1 to 2. React unmounts the old Profile, mounts a new one, and draft starts again as an empty string. Without the key, the typed note would carry over to the next user, which is a bug in most forms.
The key does not need to be unique across the whole app. It only needs to distinguish siblings that share a parent.
Choosing a key for a reset
Use a value that changes exactly when you want the reset to happen, and stays the same otherwise.
| Situation | Good key | Why |
|---|---|---|
| Editing a different record | The record's id | A new record gets a clean form. |
| Restarting a wizard or quiz | A counter you increment | Incrementing forces a fresh start. |
| Items in a reorderable list | The item's stable id | State follows the item when it moves. |
A key based on array index is a poor choice for lists that can be reordered, filtered, or have items removed. The index identifies a position, not an item. After a deletion, the state at index 1 now belongs to the item that used to be at index 2.
Do not define components inside components
Because identity includes the component's type, a component defined inside another component's body is a new function on every render. React sees a different type each time, so it unmounts and remounts it, and its state resets on every parent render.
import { useState } from 'react';
function Parent() {
const [count, setCount] = useState(0);
// Wrong: Child is a new component type on every render of Parent.
function Child() {
const [text, setText] = useState('');
return <input value={text} onChange={e => setText(e.target.value)} />;
}
return (
<>
<button onClick={() => setCount(count + 1)}>Parent renders: {count}</button>
<Child />
</>
);
}Click the button and the input empties. Move Child to the top level of the module and the state survives.
Preserving state on purpose
Sometimes you want the opposite of a reset. Two situations come up often.
- To keep state while hiding a component, render it always and hide it with CSS (for example
style={{ display: 'none' }}). Hidden this way, it stays mounted. - To keep state for something that is not currently shown, lift the state to a parent, which stays mounted. See the chapter on lifting state up.
CSS hiding keeps the whole component and its DOM in memory, so avoid it for large or numerous components.
Alternatives to key for resetting
A key is the cleanest tool, but it is not the only one. You can also reset state by hand when a prop changes, but this tends to be fragile.
import { useState, useEffect } from 'react';
function Profile({ userId }) {
const [draft, setDraft] = useState('');
// Works, but renders once with stale state before the reset takes effect.
useEffect(() => {
setDraft('');
}, [userId]);
return <input value={draft} onChange={e => setDraft(e.target.value)} />;
}This version shows the old draft for one render with the new userId, then clears it. It also resets only the state you remembered to clear. With key, every piece of state in the component and its descendants resets together, with no extra render and no code to maintain.
Common mistakes
- Expecting state to follow the JSX you wrote rather than the type and position React finds.
- Using the array index as a key in a list that changes order.
- Using
Math.random()orcrypto.randomUUID()as a key during render. A new key on every render remounts the component every time and loses state and input focus. - Nesting component definitions.
- Resetting with an effect when a key would do.
Exercise
A Form component holds useState for a text field. In App, you render <Form key={recordId} />, where recordId comes from a dropdown. A teammate changes the key to key={Math.random()} "to be safe". What happens when the user types in the form, and why?
Show answer
Every time App re-renders, Math.random() produces a new key, so React sees a different component, unmounts the old Form, and mounts a new one. Any state is reset to its initial value and the input loses focus. Typing only causes a re-render of App if App owns state that changes. If the typed value is lifted into App, each keystroke wipes the form. The key should be a stable value such as recordId, which changes only when the record changes.
Exercise
In the first example of this chapter, both branches of the ternary render <Counter /> with different label props, and the score carries over when you switch. Name two ways to make each player keep a separate score that resets on every switch.
Show answer
One way is to render them in separate slots, such as {isPlayerA && <Counter label="Player A" />} and {!isPlayerA && <Counter label="Player B" />}. The other is to give each a different key, such as <Counter key="A" label="Player A" /> and <Counter key="B" label="Player B" />. In both cases React treats the two as different components, so state resets on switch.