'Re-rendering 2 different components but with same key (React)

What would happen if I replace a react element in the component tree with an entirely new react element but both components have the same key? My understanding is that react reconciliation would cause a re-render however I'm confused on the reason for why. I thought that keys acts as a way of identification when comparing 2 elements. So if 2 different react elements share the same key, doesn't react consider them the same and not cause a re-render?



Solution 1:[1]

What would happen if I replace a react element in the component tree with an entirely new react element but both components have the same key?

If their type is different, then react will still unmount the old one, and mount the new one.

however I'm confused on the reason for why.

I'm not sure how they could have designed it any other way. If i switch from an element <Foo key={1}/> to a <Bar key={1}/>, and both of those components have arbitrary state, i can't think of a way that you could transfer the state of the first component type into the second one, while still behaving in a predictable way. Well, there's one way: you could reset the state entirely, but that's basically unmounting/remounting.

Perhaps for native dom elements they could make it work, such as going from <p key={1}/> to <div key={1}/>, but it would be weird to have it work one way for native elements and another way for custom elements.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nicholas Tower