I am referring to examples on this page and it is pertaining to React preserving state based on different conditions specific to the UI tree.
Specifically, is there any difference in the way React sees the below being rendered dynamically from a UI tree perspective?
Option 1:
return (
<div>
{isPlayerA ? (
<Counter person="Taylor" />
) : (
<Counter person="Sarah" />
)}
</div>
);
Option 2:
return (
<div>
{isPlayerA && <Counter person="Taylor" />}
{!isPlayerA && <Counter person="Sarah" />}
</div>
);
The Render Trees in both options are different.
Option1:
The Render Tree will be the same for both true and false values of isPlayerA
/*
Root
Counter
*/
Option2:
The Render Tree when isPlayerA is true
/*
Root
Counter
false
*/
The Render Tree when isPlayerA is false
/*
Root
false
Counter
*/
Now when it comes to state retention rule
Option 1 :
The state retention rule states that the state will retain when same component renders in the same position of the Render Tree.
In option 1, though the actual declaration rendered varies based on the variable isPlayerA, the same component Counter is rendered always in the same position of the Render Tree. When React compares the two Render Trees, the latest and the previous, it finds no difference and therefore the state in the previous render is retained for the latest render as well.
Option 2 :
Now let us inspect the first Render Tree. The Counter has rendered in the first place of the tree, and the second place in the tree is a hole since there is no component to render there.
/*
Root
Counter
false
*/
In the second tree, Counter comes in the second position and the first position is a hole in the tree.
/*
Root
false
Counter
*/
Now again the same state retention rules applies here: State does not retain between renders, since the component Counter changes its position on every render.
For a detailed post on the same can see over here:
How does React determine which state to apply when children are conditionally rendered?