Sub topic 7
Type and position decide whether state is kept or reset
This chapter assumes you know JavaScript, basic React components and props, useState, and the idea that React compares the previous and next element trees (reconciliation). The question here is narrow: when a component re-renders, does React keep its state or throw it away?
The rule
React stores state in the tree, not in your component function. Each piece of state belongs to a component instance at a specific position in the tree. During reconciliation, React compares the old and new element at each position:
- Same type at the same position: React keeps the instance and its state, and updates its props.
- Different type at the same position: React unmounts the old subtree, destroying its state, and mounts a new one.
"Type" means the exact component function (or the DOM tag string, such as div). "Position" means the place in the returned tree, not the place in your source file.
State survives when type and position match
import { useState } from 'react';
function Counter({ label }) {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
);
}
export default function App() {
const [isFancy, setIsFancy] = useState(false);
return (
<div>
{isFancy ? <Counter label="Fancy" /> : <Counter label="Plain" />}
<label>
<input
type="checkbox"
checked={isFancy}
onChange={e => setIsFancy(e.target.checked)}
/>
Fancy
</label>
</div>
);
}The two branches of the ternary are different elements in your source. But both are Counter at the first child position of the div. React sees the same type at the same position, so toggling the checkbox changes the label and keeps the count.
State resets when the type changes
Replace one branch with a different type, such as <p> instead of <Counter>, and the counter's state is destroyed when that branch is shown. The same happens if you wrap the component in a div in one branch only, because the type at that position changes from Counter to div.
Do not define components inside components
A common cause of unexpected resets is a component declared inside another component's body:
import { useState } from 'react';
export default function Parent() {
const [n, setN] = useState(0);
// Wrong: a new function, and so a new type, on every render
function Child() {
const [text, setText] = useState('');
return <input value={text} onChange={e => setText(e.target.value)} />;
}
return (
<>
<button onClick={() => setN(n + 1)}>Rerender parent: {n}</button>
<Child />
</>
);
}Each time Parent renders, Child is a new function. React compares types by identity, sees a different type, and remounts Child. The input loses its text whenever the parent re-renders. Move Child to module level.
Resetting state on purpose with a key
Sometimes you want a reset even though type and position match. For example, an edit form should start clean when the user switches to a different person. Give the component a key that identifies the data:
function Profile({ userId }) {
return <EditForm key={userId} userId={userId} />;
}When userId changes, the key changes, React treats the element as a different instance, and EditForm is remounted with fresh state. This is the supported way to reset state, and it is usually better than copying props into state and syncing them in an effect.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Input text disappears on parent re-render | Component defined inside another component | Move it to module level |
| Form shows the previous user's data | Same type and position, state kept | Add `key={userId}` |
| State survives a conditional switch you expected to reset | Both branches render the same component at the same position | Give each branch a different `key` |
| State resets when you add a wrapper | Wrapper changes the type at that position | Keep the wrapper in both branches |
Exercise
A Panel component holds a useState text field. A parent renders {isEditing ? <Panel mode="edit" /> : <Panel mode="view" />}. The user types text, then toggles isEditing. Is the text kept? How would you make it reset on each toggle?
Show answer
The text is kept. Both branches render Panel at the same position, so React preserves the instance and only updates the mode prop. To reset, give each branch a distinct key, for example <Panel key="edit" mode="edit" /> and <Panel key="view" mode="view" />. A changed key makes React remount the component with fresh state.