Preserving and Resetting State: React and the Position in the Tree
React does not store state in the component but at its position in the render tree – once you understand that, you control preservation and reset on purpose instead of by accident.
Preserving and Resetting State: React and the Position in the Tree
Two facts decide whether a component’s state survives an update: the position in the render tree and the component type that sits at this position. If both stay the same, React passes on the remembered state. If either of them changes, the state is discarded. There are no other criteria – and no exception for “but it’s the same component.”
This only becomes puzzling because a different picture pushes itself forward: the state lives in the component, the way a variable lives in an object. According to this picture, useState would have to hold its value where the function stands. React does not do that. When updating, it compares two trees – the old one and the new one – and derives from the differences what needs to happen in the DOM (How React renders the tree). It is exactly this comparison that also decides about the state. Two kinds of bugs grow out of the wrong picture: sometimes a state is lost that you wanted to keep, sometimes one sticks around that you wanted to get rid of.
State hangs on the position, not on the component#
The right picture is this: React does not store the state in the component but at its position in the render tree. Every spot in the tree – first child of a container, second child, the element behind this condition – is an address. At this address, React remembers which component last stood there and what state it had. If the same component stands at the same address again on the next update, React hands it the remembered state once more. If something else stands there – or nothing at all anymore – React throws away the state of this address.
That gives you the whole rule in one sentence: the same component at the same position keeps its state. If the type changes at a position, or if the position disappears, the state there is discarded. Everything else in this post is just this one rule, applied to cases that otherwise seem puzzling.
Example A: two counters, two positions#
Let’s take two identical components side by side. Both are the same Counter, written from the same function:
function Counter({ label }) {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
{label}: {count}
</button>
);
}
function App() {
return (
<div>
<Counter label="left" />
<Counter label="right" />
</div>
);
}
If you click the left one up, the right one stays put. That is irritating at first, because it is the same component – shouldn’t they share the same state? No, and the position rule immediately explains why. The left Counter sits at the address “first child of the div,” the right one at “second child.” Those are two addresses, so two separate states. That both come from the same function does not matter – the function is only the template; the state hangs on the position.
Now the case that really sharpens the point. We conditionally hide the right counter and show it again:
function App() {
const [showRight, setShowRight] = useState(true);
return (
<div>
<Counter label="left" />
{showRight && <Counter label="right" />}
<button onClick={() => setShowRight(!showRight)}>toggle right</button>
</div>
);
}
You count the right one up to 7, switch it off, switch it back on – and it is at 0. The state is gone, irretrievably. As long as showRight is false, nothing stands at the second position. React sees a position that has disappeared and clears away its state. When the Counter comes back, from React’s point of view it is a freshly occupied address, not a reunion. The state was never “in the counter” – it was bound to a position that did not exist in the meantime.
Example B: the same position, a different type#
The opposite case shows the same rule from the other side. As long as the same component type stands at a position, the state survives every change of props. You can give a Counter a different label on every update, change its color, switch it from active to inactive – the count stays, because the same type still stands at the position. Props reshape the component; they do not reset it.
If, on the other hand, the type flips at the same spot, the state is gone. This is exactly where the type rule of reconciliation applies, which I described in How React renders the tree: if React encounters a different element type at a position than before, it tears down the old subtree and builds the new one from scratch – including state. A common trigger looks harmless:
function Panel({ editing }) {
if (editing) {
return <input defaultValue="draft" />;
}
return <p>draft</p>;
}
At this position, the type switches between <input> and <p>. Every switch throws away the old node – the <input> loses its typed text, because on the next toggle a <p> stands there and after that a brand-new <input>. The same happens when one component is rendered at a spot sometimes and a different one at other times: different types at one address mean different things to React, and different things do not share state.
flowchart TB
subgraph erhalten["gleiche Position, gleicher Typ"]
A1["Counter an Position 2<br/>count = 7"] --> A2["neue Props<br/>Typ bleibt Counter"]
A2 --> A3["count = 7<br/>bleibt erhalten"]
end
subgraph reset["gleiche Position, anderer Typ"]
B1["p an Position 2"] --> B2["jetzt input<br/>an Position 2"]
B2 --> B3["alter Teilbaum weg,<br/>Zustand verworfen"]
endResetting state on purpose#
So far this sounds like a trap. But you can turn the rule around and make it a tool. Sometimes you explicitly want a reset – and then the position rule tells you exactly how to order one.
The crude way: render the component at a different position. Two branches of an if that seemingly show the same Counter are two different positions from React’s point of view if they hang at different spots in the tree; if you toggle between them, you get a fresh state every time. That works, but it is heavy-handed and easy to trigger by accident.
The elegant way goes through the key. A key tells React explicitly: “This is a specific element; distinguish it from its neighbors.” From JSX, precisely, you know keys as the thing that makes lists stable so that React recognizes the elements when reordering. But exactly the same capability also works outside of lists for a targeted reset. If an element’s key changes, React treats it as a new element at this position – the old subtree is torn down, the state created fresh.
The classic example is a form that should start fresh for each selected record:
function ContactEditor({ selectedId }) {
return <Form key={selectedId} contactId={selectedId} />;
}
Without the key, Form would stay at the same position; if selectedId changed, the form would only get new props, and the half-typed text of the previous contact would remain in the field. With key={selectedId}, the key changes with every new selection, React sees a new element, and the form starts empty – without you resetting a single field by hand. The key does exactly the work you would otherwise rebuild with an effect and lots of setState.
flowchart LR S1["selectedId = 1"] --> F1["Form key=1<br/>frischer Zustand"] S2["selectedId = 2"] --> F2["Form key=2<br/>neues Element,<br/>Formular leer"] S3["selectedId = 2<br/>Feld getippt"] --> F3["Form key=2<br/>Zustand bleibt"]
Preserving state even though the structure changes#
The counterpart is the case in which you want to keep the state but the surroundings change. Here the point is to keep position and type stable, even if things are being rebuilt around them. If you write a component into one branch or the other depending on a condition, you move it to a different position – and then wonder about the reset. Often you can avoid this by rendering the component at a fixed spot and only switching its props instead of letting it wander through the tree.
And if a state has to survive a real restructuring, it usually does not belong where it currently is. Then you lift it up to a common parent that stays untouched by the restructuring. The state then hangs on a position that is stable, and the children below it may come and go without dragging it along. This is the same move as the classic lifting of state. The reason here is a different one: it is about surviving a structural change, not about sharing between siblings.
The nastiest bug: a component inside a component#
I save the most unpleasant case for the end, because it puts the position rule to the test and because it hides in real codebases surprisingly often. It looks like this:
function Page() {
function Sidebar() {
const [open, setOpen] = useState(true);
return <button onClick={() => setOpen(!open)}>{open ? "hide" : "show"}</button>;
}
return (
<div>
<Sidebar />
</div>
);
}
Sidebar is defined inside Page. That looks tidy – after all, the component stands where it is needed. The effect is devastating nonetheless. On every render of Page, the line function Sidebar() runs again and creates a new function. On every pass, it is literally a different function with a different identity. For React, however, the identity of the function is the type. A different type at a position means: old subtree gone, new one built, state discarded.
In practice, this looks eerie. Every update of Page, however small, resets open, the input field inside loses its text, and if you are typing in a field, you lose focus mid-word because the DOM element under you was replaced. You search for the bug everywhere – in the effect, in the event handler, in the state management – except at the spot where the component is defined. And yet that is exactly it: a function identity reborn on every render that forces React to throw away the whole subtree.
The solution is unspectacular and therefore easy to overlook: components belong at the module level, not in the body of another component. Then Sidebar exists exactly once, keeps the same identity across all updates, stands as the same type at the same position – and its state stays. If the inner component needs data from outside, you pass it in as props, not via the nested definition.
Place and time in the tree#
State in React is bound to place and time: to a position in the render tree and to the duration for which this position stays occupied by the same type. Almost everything that seems puzzling about the behavior of state clears up as soon as you stop asking “which component is this in?” and instead ask “at which position in the tree, and does the same type still stand there?”
Once you have internalized this, you have both directions in hand. You order a reset with a key or a new position instead of resetting fields one by one. You secure preservation by keeping position and type stable and, if necessary, lifting the state up. And you avoid the nastiest bug before it arises by keeping components where they belong – at the module level. That turns something that felt like magic into a decision you make on purpose instead of suffering it by accident.
Further reading#
- Repository introduction-react: https://github.com/mikebild/introduction-react
- React, “Preserving and Resetting State”: https://react.dev/learn/preserving-and-resetting-state
- React, “State as a Snapshot”: https://react.dev/learn/state-as-a-snapshot
- React, “Render and Commit”: https://react.dev/learn/render-and-commit
Revised and translated from German with the help of AI.