79316816

Date: 2024-12-30 04:37:10
Score: 0.5
Natty:
Report link

The two Render Trees 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?

Reasons:
  • Long answer (-1):
  • Has code block (-0.5):
  • Ends in question mark (2):
Posted by: WeDoTheBest4You