Preserving and Resetting State
This is the summarization of React docs
?? React preserves a component’s state for as long as it’s being rendered at its position in the UI tree. If it gets removed, or a different component gets rendered at the same position, React discards its state.
when you render a different component in the same position, it resets the state of its entire subtree
?? if you want to preserve the state between re-renders, the structure of your tree needs to “match up” from one render to another. If the structure is different, the state gets destroyed because React destroys state when it removes a component from the tree.
Specifying a key tells React to use the key itself as part of the position, instead of their order within the parent.
Recap