{isPlayerA && <Counter person="Taylor" />}
{!isPlayerA && <Counter person="Sarah" />}
When isPlayerA is true,the Virtual DOM looks like:
[
<Counter person="Taylor">, //FIRST CHILD
false //SECOND CHILD(ignored in real DOM)
]
When isPlayerA becomes false,the virtual DOM changes to
[
false, //FIRST CHILD(ignored in real DOM)
<Counter person="Taylor"> //SECOND CHILD
]
Even though <Counter>
is at the same position in the code, its position in the Virtual DOM has shifted.
The first child changed from <Counter>
to false, so React unmounts(removes) <Counter person="Taylor" />.
The second child changed from false to <Counter>,
so React mounts(adds) a new <Counter person="Sarah" />
.
Since <Counter person="Taylor" />
is completely removed, its state is lost.
Since <Counter person="Sarah" />
is completely new, it gets a fresh state.
///////////////////////////////////////////////////////////////////////////
{isPlayerA ? <Counter person="Taylor" /> : <Counter person="Sarah" />}
In this case ,<Counter>
is always the first child in the Virtual DOM. React sees that only the prop changes ("Taylor" to "Sarah"), so it updates the prop instead of unmounting the component.
Note: false
do not create actual nodes in the real DOM. false
does exist in the Virtual DOM, affecting reconciliation