React stores state in its own tree, at the position where the component renders ("the first child of the <div> that App returns"), not in the function or the JSX tag. Each render matches the new element at that position with the old one:
- Same type, position and key → state is kept, even if props change.
- Removed → state is gone. Rendering it again later starts from the initial state.
- Different type at that position → reset, for its whole subtree; that includes an ancestor changing type.
- Different key → reset, even with the same type at the same position.
Position means the returned tree, not where JSX sits in your code:
{isA ? <Counter name="A" /> : <Counter name="B" />}keeps the state: one slot, one counter whose props changed.{isA && <Counter name="A" />}{!isA && <Counter name="B" />}resets it. These are two slots;falseholds the empty one, so each counter mounts and unmounts.- Two
returnstatements that each put<Counter />first in a<div>are the same position too.
Resetting on purpose. When different data means a different thing, such as a chat with another contact, give the component a key from that identity: <Chat key={contact.id} contact={contact} />. A new key unmounts the old subtree and mounts a fresh one: state, DOM and effects start over, all the way down. That replaces an effect that resets state when a prop changes.
Resetting by accident. A component defined inside another component is a new function, and therefore a new type, on every render of its parent, so its state and DOM are thrown away each time. Define components at the top level.
To keep state for hidden UI, lift it up or hide it with <Activity>.