Capítulo 30 de 116
React preserves a component's state for as long as that same component type renders at the same position in the tree across renders — change either the position or the type at that position, and React discards the old state and mounts fresh, regardless of what the JSX "looks like" it's doing.
<Counter /> calls in different JSX branches of an if/else are still "the same position" if they render into the same slot of the parent tree — so toggling between them preserves state rather than resetting it, which often surprises people who expect each JSX line to be independent.useState intact.<Counter /> for <div> (or for a completely different component) at the same tree position destroys the old subtree and mounts a brand-new one from scratch, resetting all its state — because React's identity check is by component type, not by "this general area of the screen."key — changing the key value forces React to treat it as a different element even though the type and position are unchanged, so it unmounts the old instance and mounts a new one.key as a state-reset lever generalizes the list key behavior from Ch 17 — any component, not just list items, can be forced to reset by changing its key, which is the standard trick for "restart this form/component from scratch" (e.g. a chat input keyed by the currently open conversation's id).// Force a fresh Form instance (state reset) whenever the recipient changes
<Chat key={recipient.id} recipient={recipient} />
key deliberately to reset a component's internal state when the logical "identity" of what it represents changes, even though its position in the tree stays the same.key is the standard, intentional way to force a full remount/state-reset without restructuring your component tree.key was introduced, for list identity.