Sub topic 7
Type and Position Decide Whether State Is Kept or Reset
This chapter assumes you know how to write function components, pass props, and use useState. It also assumes you have read the previous chapter on reconciliation, where React compares the previous element tree with the next one. Here you will see exactly how that comparison decides whether a component keeps its state or loses it.
State belongs to a position in the tree
State does not live inside your component function. React stores it alongside the tree it builds, and it attaches each piece of state to a spot in that tree. When a component renders, React looks at the spot where it appears and asks one question: is the same kind of thing already here?
- If the same component type is at the same position, React keeps the existing instance and its state. It passes the new props to it.
- If a different type is at that position, or nothing was there before, React discards the old subtree and creates a new one. All state in the old subtree is lost, and the new components start from their initial state.
This explains a result that surprises many people: state follows the tree position, not the line of JSX in your source file.
The rules React applies
When React compares an old element with a new element at the same position, it checks the element's type.
| Old element at this position | New element at this position | Result |
|---|---|---|
| `<Counter />` | `<Counter />` | Same instance. State is kept. Props are updated. |
| `<Counter />` | `<Other />` | Counter is unmounted. Other is mounted fresh. |
| `<div>` | `<section>` | The DOM node and everything inside it is destroyed and rebuilt. |
| `<input className="a" />` | `<input className="b" />` | Same DOM node. Only the changed attribute is updated. |
| `<Counter key="a" />` | `<Counter key="b" />` | Different keys, so different identity. State is reset. |
Two details are worth noting:
- Comparison is by type identity, not by name or appearance. Two components with identical code but different function objects are different types.
- The rule applies recursively. If a parent's type changes, every descendant is unmounted, even if the children look the same.
Example: state is kept when the position is the same
A common pattern switches between two views with a conditional. Consider a counter whose style depends on a flag.
import { useState } from 'react';
function Counter({ label }) {
const [score, setScore] = useState(0);
return (
<div>
<h3>{label}: {score}</h3>
<button onClick={() => setScore(score + 1)}>Add one</button>
</div>
);
}
export default function Scoreboard() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<div>
{isPlayerA ? (
<Counter label="Player A" />
) : (
<Counter label="Player B" />
)}
<button onClick={() => setIsPlayerA(!isPlayerA)}>
Switch player
</button>
</div>
);
}Click "Add one" a few times, then click "Switch player". The heading changes to "Player B", but the score stays where it was. The two <Counter> elements are written in different branches of the ternary, yet React sees one Counter at the same position in the output of Scoreboard. It keeps the instance and only updates the label prop.
The reverse also happens. If you want two separate scores, you must tell React they are different things.
Resetting state: two ways
Option 1: render them in different positions
If both counters can exist at once, give each its own position.
import { useState } from 'react';
function Counter({ label }) {
const [score, setScore] = useState(0);
return (
<div>
<h3>{label}: {score}</h3>
<button onClick={() => setScore(score + 1)}>Add one</button>
</div>
);
}
export default function Scoreboard() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<div>
{isPlayerA && <Counter label="Player A" />}
{!isPlayerA && <Counter label="Player B" />}
<button onClick={() => setIsPlayerA(!isPlayerA)}>
Switch player
</button>
</div>
);
}Each && expression occupies its own slot among the children of the div. When isPlayerA is true, slot 0 holds a Counter and slot 1 holds false. After the switch, slot 0 holds false and slot 1 holds a Counter. React sees slot 0 lose its component, so it unmounts it, and a new Counter mounts in slot 1 with a score of 0.
React keeps a slot for false, null, and undefined. They render nothing, but they still hold the position, which is why the slots do not shift.
Option 2: give the component a key
A key is an identity label. It is not only for lists. When the key changes, React treats the element as a different instance, even at the same position and with the same type.
import { useState } from 'react';
function Counter({ label }) {
const [score, setScore] = useState(0);
return (
<div>
<h3>{label}: {score}</h3>
<button onClick={() => setScore(score + 1)}>Add one</button>
</div>
);
}
export default function Scoreboard() {
const [isPlayerA, setIsPlayerA] = useState(true);
return (
<div>
{isPlayerA ? (
<Counter key="A" label="Player A" />
) : (
<Counter key="B" label="Player B" />
)}
<button onClick={() => setIsPlayerA(!isPlayerA)}>
Switch player
</button>
</div>
);
}Now each switch destroys the old Counter and mounts a new one. Use this approach when only one instance is on screen at a time, as in a form that edits one record. Passing key={userId} to an edit form is the standard way to reset it when the selected user changes. It is simpler and safer than writing an effect that copies props into state.
Component definitions inside components
The "same type" check compares function identity. This leads to a bug that is easy to write.
import { useState } from 'react';
export default function Page() {
const [count, setCount] = useState(0);
// Wrong: a new function object is created on every render of Page.
function Panel() {
const [text, setText] = useState('');
return (
<input value={text} onChange={e => setText(e.target.value)} />
);
}
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Panel />
</>
);
}Each time Page re-renders, Panel is a brand-new function. React compares the old Panel with the new one, sees different types, and unmounts the old one. The input loses its text and its focus every time you click the button. The fix is to define Panel at the top level of the module, outside Page, so its identity never changes.
What gets destroyed
Removing a subtree has real costs beyond state:
- Local state from
useStateanduseReduceris lost. - Effect cleanup functions run on unmount, and the effects run again on the new mount.
- DOM nodes are removed, so scroll position, text selection, focus, and uncontrolled input values inside are lost.
- Anything held in refs inside that subtree is gone.
State in a parent, in a context provider above, or in an external store is not affected. Only the subtree below the changed position is.
Preserving state on purpose
Sometimes you want state to survive when a component is hidden. There are three common approaches.
- Keep it mounted and hide it with CSS (
display: none). The state, DOM, and effects remain, but the hidden component still takes part in rendering. - Lift the state up to a parent that stays mounted, so the child can be unmounted and remounted with the same values.
- Store the state in a more durable place, such as a store or
localStorage.
Choose based on cost. Keeping many large hidden trees mounted uses memory and render time. Lifting state up is usually the cleanest answer.
How the decision flows
The following diagram shows the choice React makes for each position.
Common errors
- Expecting two ternary branches to be separate. Two elements of the same type in the same slot share state. Add a key or use separate slots.
- Defining components inside components. This causes constant remounts. Move the definition to module scope.
- Wrapping and unwrapping. Changing
<Counter />to<div><Counter /></div>changes the type at that position fromCountertodiv, so the counter remounts. Keep wrapper structure consistent when state must survive. - Using the array index as a key when the list changes order. The key is the same at each position, so state sticks to the slot, not to the item. The next chapter covers keys in lists.
- Copying props into state.
useState(props.value)only reads the prop on mount. If the instance is kept, the state does not follow later prop changes. A key on the component is the usual fix.
Exercise
A Form component holds a text input in state. A parent renders <Form userId={id} /> and the user switches id from 1 to 2. The typed text from user 1 still shows for user 2. Name the cause and give the smallest change that resets the form.
Show answer
React sees the same type (Form) at the same position, so it keeps the instance and its state and only updates the userId prop. Pass a key that changes with the user: <Form key={id} userId={id} />. The changed key makes React unmount the old form and mount a new one with fresh state.
Exercise
A component renders {isOn ? <Panel /> : <Panel />}, and a different developer renders {isOn ? <Panel /> : <div><Panel /></div>}. In which version does Panel lose its state when isOn flips, and why?
Show answer
The second version. In the first, both branches produce a Panel at the same position, so the instance and its state are kept. In the second, the position holds a Panel in one case and a div in the other. The type differs, so React unmounts the old subtree and the Panel inside the div mounts fresh with initial state.