Back to results for “State Management”
React › Virtual DOM & Reconciliation

Why does changing an element's key prop cause React to completely remove and recreate that element instead of just updating it?

Advanced

Answer

React uses the key prop as a strong signal of identity for elements in a list or a set of siblings. If the key changes, React assumes it is looking at a genuinely different element, not an update to the same one, so it removes the old element entirely, including losing any of its internal state, and creates a brand new one from scratch.
// Changing the key forces React to fully recreate this component,
// resetting any internal state it had, like an open accordion section
<Accordion key={selectedCategory} category={selectedCategory} />
Real-world example A settings panel intentionally changes a component's key whenever the user switches to a completely different section, forcing React to fully reset that component's internal state rather than accidentally carrying over old, now irrelevant state.

Common follow-ups: How could you deliberately use this behavior to force a component to fully reset when a specific prop changes?;What is the performance cost of forcing React to recreate a component this way?